i'm currently working on a project that would have a database of reports of a scam. In the report section of the website I have a form, but I want anyone to be able to add multiple profiles with a click of a button. For example:
Nickname field: xyz
Steam profile: x
[ + ] <- button for adding more profiles, which when pressed would look something like this:
Nickname field: xyz
Steam profile: x
Steam profile 2: y [ Delete ]
[ + ]
I was looking into FormSets and Inline Formsets, but nothing turned up that would match this specific need, aswell as did not answer the question regarding storing the results of the form.
How would I go about creating the form for this?
How would I store the multiple results of Steam profile to my object that has a steam_profile = models.CharField?
My current model:
class Scammer(models.Model):
#Basic information for display
steam_id_64 = models.CharField(max_length=17, default='00000000000000000')
nickname = models.CharField(max_length=64, default='Nickname')
steam_profile = models.CharField(max_length=512, default='https://www.steamcommunity.com')
description = models.TextField(default='')
proof = models.TextField(default='')
#Date created var for ordering
date_created = models.DateTimeField(default=timezone.now, blank=True)
def __str__(self):
return self.nickname
def get_absolute_url(self):
return reverse('dashboard-home')
My view:
class ScammerCreateView(CreateView):
model = Scammer_Unapproved
template_name='dashboard/report.html'
fields = ['nickname', 'steam_id_64', 'steam_profile', 'description', 'proof']
My template:
{% block content %}
<div class="report-scammer">
<form method="POST">
{% csrf_token %}
<fieldset>
<legend>Report a scammer</legend>
{{ form|crispy }}
</fieldset>
<div>
<button type="submit">Report</button>
</div>
</form>
</div>
{% endblock content %}
Have the profiles as the Builtin Django User model or maintain a separate model with a link to the inbuilt User model. Now the scam report form can have the option to be linked to Multiple User accounts by using ManytoMany relationship field. check the below official documentation page,
[https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/][1]
Related
I'm trying to make a favorite functionality where an user can add other users as their favorites.
In the View where the profile of an user is shown I have a button that adds an user or removes it if it was already added.
The problem is that I can't pass to the views the user that will be added as a favorite.
models.py
class User(AbstractUser):
is_type1 = models.BooleanField(default=False)
...
class Type1(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
favorite = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name='favorite')
views.py
def FavoriteView(request, pk):
current_user = request.user
Type1.user = current_user.id
buser = Type1.user
Type1.favorite = get_object_or_404(User, id=request.POST.get('username')) # The of the error where I try to add the user being added as a favorite
fuser = Type1.favorite
if Type1.favorite.filter(id=request.user.id).exists():
Type1.favorite.remove(request.user)
else:
Type1.favorite.add(request.user)
return HttpResponseRedirect(reverse('profile-details', kwargs={'username': Type1.favorite}))
class UserView(DetailView):
model = User
...
template_name = 'users/profile-details.html'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
favorite_connected = get_object_or_404(Type1.favorite, id=self.kwargs['username']) # The of the error where I try to add the user being added as a favorite
favorite = False
if favorite_connected.favorite.filter(id=self.request.user.id).exists():
liked = True
data['user_is_favorite'] = favorite
return data
profile-details.html
...
{% if user.is_authenticated %}
<form action="{% url 'favorite' object.id %}" method="POST">
{% csrf_token %}
{% if user_is_favorite %}
<button type="submit" name="favorite" value="{{object.id}}">Not favorite</button>
{% else %}
<button type="submit" name="favorite" value="{{object.id}}">Favorite</button>
{% endif %}
</form>
{% else %}
Log in to add user to favorites.<br>
{% endif %}
urls.py
path('profile/<str:username>/', UserView.as_view(), name='profile-details'),
path('favorite/<str:username>/', FavoriteView, name="favorite"),
One immediate problem I see is that your URL path wants a string for the username, but your URL for the form gives it the ID of the user, so that'll be an int.
In terms of your error, you're trying to pass a username, but I don't think that'll be in the POST data. However if it was, you should be able to do;
get_object_or_404(User, username=request.POST.get('username'))
However, based on my initial comment, you should probably just get the user by ID like you are doing, but use the PK of the user which is comes with your view;
get_object_or_404(User, id=pk)
You may also come across more errors, because you're assigning an object, if it exists to Type1.favorite and then attempting to do Type1.favorite.filter( which will fail. You can only .filter() on a queryset, not a model instance.
I am new to django and building an user (named "Developer") settings update page. I used model form and passed the settings instance via views.py hoping them to show up in the rendered template for users (named "Developer") to edit. But the instance value is not populated into the template in form.as_p.
I have tested the {{project_form.instance.pk}} is passing the correct project instance, so I am expecting the project name to show up as default value in the form for user input project name, but it is showing blank.
models.py (simplified)
class Project(models.Model):
project_name = models.TextField(unique=True)
class Developer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
project = models.ForeignKey(Project, on_delete=models.CASCADE, default=Project.get_default_project)
institution = models.ForeignKey(Institution, on_delete=models.CASCADE, null=True, blank=True)
forms.py
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['project_name']
views.py
def developerSettingsUpdate(request):
from .forms import ProjectForm
developer = request.user.developer
project = developer.project
if request.method == 'POST':
project_form = ProjectForm(request.POST, instance=project)
if project_form.is_valid():
project_form.save()
else:
project_form = ProjectForm(instance=project)
return render(request,
'decg/developer_settings.html',
{
'project_instance': project,
'project_form': project_form,
})
developer_settings.html
<div>
<h5>Expecting this field to show instance: {{ project_form.instance.project_name }}</h5>
</div>
<form method="post">
{% csrf_token %}
{{ project_form.as_p }}
<button class="button" type="submit">Update</button>
</form>
But it is showing blank: see Screenshot of rendered developer_settings.html:
see Screenshot of rendered developer_settings.html
The problem lies in this code:
developer = request.user.developer
project = developer.project
Those variables must point to an actual model instance in order to populate the form like you did in project_form = ProjectForm(instance=project) . It should be something like this:
developer = Developer.objects.filter(user=request.user.developer)
project = Project.objects.filter(project_name=request.user.developer)
Started of learning Django python a week or two ago, so please keep this in mind.
What I want is for data to be displayed in forms and it will be edited with in the same forms, for example:
enter image description here
Where it says:
First Name
Last Name
email
I would like it to pull the data from the database and have it written out inside of forms.
First Name Kevin
Last Name Clark
email Kevin.clark#gmail.com
and so on for each entry.
Like it is written down bellow where it says you created these.
So one editing form with values written out for each set of entry's.
I hope that I have managed to pose a clear question and I do not believe to the best of my knowledge that it is a duplicate, if it is I am so sorry.
OS:Fedora
IDE:Eclipse
Django Python
views.py
def edit(request):
instance = New.objects.all()
data = { "firstName" : "Clark",
"lastName": "Kevin"}
form = NewForm(request.POST) #instance=instance)
print form.instance.firstName
if(form.is_valid()):
instance = form.save(commit=False)
instance.save()
context = {
"object_list" : instance,
"formset" : form,
"instance" : instance
}
return render(request, "secondTry/new.html", context)
models.py
class New(models.Model):
firstName = models.CharField(max_length=50, null=True)
lastName = models.CharField(max_length=50, null=True)
email = models.EmailField()
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
forms.py
class NewForm(ModelForm):
class Meta:
model = New
fields = [
"firstName",
"lastName",
"email"
]
html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Create a New One</h1>
<form method='post' action=""> {% csrf_token %}
<table>
{{ formset }}
</table>
<input type='submit' value="Submit">
</form>
{{ instance }} {% csrf_token %}
<h2>You Created These</h2>
{% for obj in object_list %}
{{ obj.firstName }}
{{ obj.lastName }}
{{ obj.email }} <br/><br/>
{% endfor %}
</body>
</html>
Note, I am not using all the variables in def edit as I am going back and forth trying to figure this out so it might be a bit messy.
Thank you all so much for your time.
If I'm understanding your question correctly, you just want the initial values to show up in the form? In that case you're looking for https://docs.djangoproject.com/en/1.9/ref/forms/api/#dynamic-initial-values
When you're creating an instance of your Form, do something like name_form = Form(request.POST, initial=db_instance)
Assuming that your edit view is already loading the instance from the DB somehow.
I am creating a very simple to-do list application. Each user should have an associated to-do list page with basic CRUD functionality. That means User A should have different data than User B.
As of right now there is no distinction about who owns the to-do list. Anyone who is logged in can add, remove, display, delete tasks.
I have a gut feeling that I might need an extra something in my model and my template. I should mention that I use Pinax 0.9a2. If it does what I need it to do, I would prefer to use that solution instead.
Here's my models.py
class Task(models.Model):
name = models.CharField(max_length=100)
added_at = models.DateTimeField(auto_now_add=True)
last_update = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
Here's one of my forms in views.py
def task_create(request):
return create_object(request,
model=Task,
template_name='task_create.html',
post_save_redirect=reverse("todo_list")
)
Here's 2 of my templates:
To-Do Create
<form action="" method="post">{% csrf_token %}
{{ form.name }}
<button type="submit" class="btn primary">Create →</button>
</form>
To-Do List
{% if task_list %}
<p>Create a task</p>
<ul>
{% for task in task_list %}
<li>{{ task.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No tasks to display, click to create new.</p>
{% endif %}
So you just want to add access control to it?
Add ForeignKey to auth.User to your ToDos model
Rewrite your list and create views to make their work manually (you can achieve your goal with new class based views but you need to understand how do they work first)
Add filter for queryset in list view
Provide commit=False to your form's save(), set up user for retrieved object and save it manually
Code:
class Task(models.Model):
user = models.ForeignKey('auth.User')
name = models.CharField(max_length=100)
added_at = models.DateTimeField(auto_now_add=True)
last_update = models.DateTimeField(auto_now=True)
class TaskForm(forms.ModelForm):
class Meta:
model = Task
exclude = ['user', ]
def task_create(request):
form = TaskForm(data=request.POST or None)
if request.method == 'POST' and form.is_valid():
task = form.save(commit=False)
task.user = request.user
task.save()
return reverse("todo_list")
return render(request,
'task_create.html',
{'form': form}
)
Also, add filtering by request.user in list view and I'd recommend #login_required decorator to avoid adding tasks by non-authorized users.
I'm working on my first Django project and employing django-registration and django-profiles. The former worked beautifully with nary an issue. The second has been a bit more problematic.
After many hours, specific user profiles can finally be viewed, which is terrific, along with a list of all profiles.
The two issues I'm encountering: django-profiles will not automatically create a new profile when a new user is created. Once a user is created in the admin, a profile should be created. That isn't occurring.
In addition, the profiles/edit_profile form results in this error:
"TemplateSyntaxError at /profiles/edit/ Caught NoReverseMatch while rendering: Reverse for 'edit_profile' with arguments '(,)' and keyword arguments '{}' not found."
I've searched for answers to these issues to no avail.
This is the model for the profile in my app file:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=35)
email = models.EmailField()
birth_date = models.DateField(blank=True, null=True)
city = models.CharField(max_length=25)
state = models.CharField(max_length=20)
zip_code = models.CharField(max_length=10)
def __unicode__(self):
return " %s" % (self.user)
def get_absolute_url(self):
return ('profiles_profile_detail', (), { 'username': self.user.username })
get_absolute_url = models.permalink(get_absolute_url)
This is my form:
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
This is the template:
{% extends 'base.html' %}
{% block page_title %}Edit Profile{% endblock %}
{% block headline %}Edit Stentorian Profile{% endblock %}
{% block content %}
<form action="{% url edit_profile user %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
Interested in learning what errors I made and how to fix these. (I realize the user object carries first and last name, but there appears no other way to insert these into the profile other than with their own specific fields).
Any insight appreciated.
Edit: It seems to have worked out thanks to The Missing Manual. Unfortunately, /profiles/edit now bounces to /profiles/create. Not sure of this issue.
Here is a link to help you with this.
django-profiles the missing manual
Scroll down to NO MISSING PROFILES! section. Here they explain that to create a profile must be done with a signal whenever a User instance is created.