Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Logout in django & why taking get method
Got the following weeor ValueError at /logout The view app.views.logout didn't return an HttpResponse object. It returned None instead. Request Method: GET i dont know why its taking get method Request URL: http://127.0.0.1:8000/logout Django Version: 3.0.8 Exception Type: ValueError Exception Value: The view app.views.logout didn't return an HttpResponse object. It returned None instead. my code is def logout(request): if request.method=="POST": auth.logout(request) return redirect('login') my html is <li class="nav-item mr-3"> <form id="logout" method="POST"> {% csrf_token %} <input type ="hidden"> </form> <a class="nav-link" href="{% url 'logout'%}" onclick="javacript:document.getElementById('logout').submit()"> Logout </a> </li> -
No name 'BlogListView' in module 'blog.views'
The code in the urls.py file is: #blog/urls.py from django.urls import path from .views import BlogListView urlpatterns = [ path('', BlogListView.as_view(), name='home'), ] The code in views.py is : #blog/views.py from django.shortcuts import render # Create your views here. After this I get the error in urls.py that ((No name 'BlogListView' in module 'blog.views')) I have searched for many documents but can't find the appropriate result -
How to update a django-rest-auth custom user?
Basically, I have used the default APIs to be consumed by the React frontend, and succeeded it until updating the user account whereas both PUT and PATCH method would return the original value rather than updating the user account. The promise response was fulfilled with code 200 and the promised object was the original value. And since, I want to include some functionality like user profile image and other custom fields, I decided to follow along this tutorial. However, it only shows how to use username instead of email. Since I am not familiar with managers, I left it untouched and rather created a new basic serializer and added new fields to my user model. Then, I admin.site.register it in the app's admin. So, in the admin panel, I see a new Users in the list along with the default "accounts". Both email addresses and Users have the same account, but superusers are not included in the email addresses. serializers.py models.py The story goes on searching the web for hours and finally found this stackoverflow answer. Unfortunately, he only shows how to add a custom field in registration. However, in my case, I want the registration to be minimal requesting … -
How to get URI template in django?
I need to get original uri template with regex from resolve function in view or middleware. For example: def view(request): uri_path = resolve(request...) # and uri_path must be equals something like 'articles/<int:year>/<int:month>/' ... Is this possible? I didn't found information about this -
Django form_valid() in CreateView not executing when try to create new dish
In this code, form_valid() function inside DishCreareView not executing when I try to create new dish.ie I am unable to create new dish,when I click on create button page url not changes and remains the same. For detecting this I have put print statement inside form_valid() but this is not executed.Please help me out. Thanks models.py class Dish(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='dishes_pics') description = models.TextField() ingredients = models.TextField(blank=True) required_time_to_cook = models.CharField(max_length=100) favourite = models.ManyToManyField(User, related_name='favourite', blank=True) cuisine_id = models.ForeignKey(Cuisine, on_delete=models.CASCADE) user_id = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('dish-detail', kwargs={'pk': self.pk}) def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) views.py class DishCreateView(LoginRequiredMixin,CreateView): model = Dish fields = ['name', 'image', 'description','required_time_to_cook','cuisine_id','user_id'] def form_valid(self, form): form.instance.user_id = self.request.user print('self==========form==create=====',form) return super().form_valid(form) form_template.html {% extends "cookbook/base.html"%} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Add Dish </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Create</button> </div> </form> </div> {% endblock content %} dish_detail.html {% extends 'cookbook/base.html' %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href="{% static 'cookbook/dish.css' %}"> <div … -
Django: How to get ForeignKey for querying
I am building a project that gives notifications for each user object. My code is: models.py for user class CustomUser(AbstractBaseUser): user_id = models.CharField(default=generate_unique_object_id, primary_key=True, max_length=24) models.py for notifications class Notifications(models.Model): user = models.ForeignKey(CustomUser, verbose_name="shared_by", null=True, blank=True) document = jsonfield.JSONField(blank=True) I want to query the database through the Notifications model. Something like this: def get_notifications(user, number_of_notifications): try: notifications = Notifications.objects.select_related('user').get(user_id = user) #incorrect for notif in range(number_of_notifications): return notifications.document So basically, I want to get the user_id corresponding to the CustomUser's user_id through the Notifications model, but I'm not quite sure how to do it. Once I get the corresponding user_id, I need the Notifications model to extract the document field comprising the actual notifications. Any help would be appreciated, thanks. -
Django Edit_post view "The current path, 15/edit_post/, didn't match any of these. "
I'm trying to edit my posts, i get this not very detailed error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/15/edit_post/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ users/ [name='post_list'] tag/<slug:tag_slug>/ [name='post_list_by_tag'] new_post/ [name='new_post'] <int:year>/<int:month>/<int:day>/<slug:post>/ [name='post_detail'] <int:post_id>/share/ [name='post_share'] edit_post/<int:post_id>/ [name='edit_post'] The current path, 15/edit_post/, didn't match any of these. views.py (edit_post view only): def edit_post(request, post_id): """Edit an existing entry.""" post = Post.published.get(id=post_id) if request.method != 'POST': # Initial request; pre-fill form with the current entry. form = EditPostForm(instance=post) else: # POST data submitted; process data. form = EditPostForm(instance=post, data=request.POST) if form.is_valid(): form.save() return redirect('blog:post_detail', post_id=post.id) context = {'post': post, 'form': form} return render(request, 'blog/edit_post.html', context) edit_post.html: {% extends 'blog/base.html' %} {% load bootstrap4 %} {% block title %} <h3><a href="{% url 'blog:post_detail' post.id %}">{{ post.title }}</a> </h3> {% endblock title %} {% block content %} <h4>Edit Post:</h4> <form method="post" action="{% url 'blog:edit_post' post.id %}" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn btn-primary">Save changes</button> {% endbuttons %} </form> {% endblock content %} forms.py from django import forms from .models import Comment, Post class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() … -
Uploading an image file to database
I am making a social media app and i am adding a edit profile function to it. But for some reason, the profile image which the user chooses is not being uploaded to the database. Please help me to do so. My views.py def edit_profile(request): user = request.user user_profile = profile.objects.get(user__username=user) Profile = user_profile myuser = User.objects.get(username=user) if request.method == 'POST': try: username = request.POST['username'] name = request.POST['name'] email = request.POST['email'] image = request.FILES['img'] myuser.username = username myuser.first_name = name myuser.email = email myuser.save() Profile.user = myuser.username Profile.name = myuser.first_name Profile.img = image Profile.save() return redirect('/') except: return redirect('/') else: context = { 'user':user_profile, 'myuser':myuser, } return render(request, 'edit_profile.html', context) my tempateview <form action="/users/edit_profile/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <center> <img src="{{user.img.url}}" style="border-radius: 50%; widows: 150px;height:150px; margin-left:-50px" onclick="document.getElementById('image').click()"><br> <span class="click" onclick="document.getElementById('image').click()">Change Profile Picture</span> </center> <input type="file" name="img" id="image" accept="image/*" style="display:none"><br><br> <label> &nbsp;Username </label><br> <input type="text" name="username" class="edit" value="{{user.user}}" spellcheck="false"><br><br> <label> &nbsp;Name </label><br> <input type="text" name="name" class="edit" value="{{user.name}}" spellcheck="false"><br><br> <label> &nbsp;Email </label><br> <input type="email" name="email" class="edit" value="{{myuser.email}}" spellcheck="false"><br><br><br> <input type="submit" value="Save changes" style="width:40%; float:right; margin-right:120px"> </form> my models.py class profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) img = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return "Profile({})".format(self.user.username) Everything is working. Only the image … -
Django: speed up hundreds of users upload
Problem I am currently developing an app and deploying it on Heroku. One important function is that the admin should be able to upload hundreds of users at a time by uploading a .csv file. The problem is that, using Heroku's free plan due to budget constraints, it is taking too long and the request time ran out. I need a better solution to deal with this problem. My Attempt My current practice now is that I use create_user() to register new user to the database (code attached below). def register_user(upload_file, file_type): if file_type == 'csv': reader = csv.reader(StringIO(upload_file), delimiter=',') for i, row in enumerate(reader): if i == 0: continue else: username = row[0] password = row[1] if username.isdigit(): is_staff = False else: is_staff = True try: User.objects.create_user(username=username, password=password, is_staff=is_staff) except: continue The reason I don't use bulk_create() is that I have to keep track of how many users are skipped/not added to the database. (Though this may not be the best practice.) Some Discovery My attempt works completely fine in localhost. With ~300 users, it takes around 10 seconds. From this thread, I already understood that the create_user() is taking too long due to the process of making passwords. … -
How to delete product from Wishlist in Django?
I have wishlist table in my Django database, and customer related to wishlist table, it means if a customer is logged in then he/she can add product in wishlist, but i am trying to delete product from customer wishlist, but it's redirecting back, please let me know how I can delete products from customer wishlist. here is my models.py file... class Wishlist(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) def __str__(self): return str(self.id) here is my views.py file... def deletewishlist(request, id): customer=request.user.customer Wishlist.objects.filter(customer_id=customer.id, id=id).delete() messages.success(request, 'Product Remove From Wishlist...') return HttpResponseRedirect('/wishlist') here is my urls.py file... path('wishlist_item/deleteproduct/<int:id>', views.deletewishlist, name="deletewishlist"), here is my delete button code, which delete products from wishlist when click... <a class="primary-btn" href="/wishlist_item/deleteproduct/{{item.product.id}}" onclick="return confirm('Are you sure')">Delete</a> -
Create two different kind of user type
I am new to django. I want to create two different users for my app. Vendors and Customers. I am using signal to create their profile but when I use signals to save, two different profiles are created. Is there a way to create one profile without creating another? Thank you! -
NGINX gives 502 error from browsers but not from Postman
I've got a Django application running on Azure App Service using NGINX. My nginx.conf file is as follow: user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; keepalive_timeout 65; fastcgi_max_temp_file_size 0; fastcgi_buffers 128 2048k; fastcgi_buffer_size 2048k; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; server { listen 8000; location / { include uwsgi_params; uwsgi_pass unix:///tmp/uwsgi.sock; } location /static { alias /app/staticfiles; } } } daemon off; Everything works fine, except for one particular API where I include in the header some token (typical bearer token) and it's returning a 502 error from Chrome (in the network tab) However, when I try to call this from Postman, it's returning the data correctly. What could be possibly wrong here? -
Failing to upload video from ReactJS to Django
Hey so I am busy with a ReactJS & Django project, I would love to upload videos on this app that I am doing, so I tried two different methods and all did not work I do not know where my implementation is wrong. Method1: Here I used the fetch to make a POST request to the URL http://127.0.0.1:8000/api/upload-lecture/ With this method, I had an onChange event listener so to change the state of the video property then, right away put every captured content from form to the FormData the make POST request Code Below: uploadVideo = (e) => { e.preventDefault(); console.log(this.state); let form_data = new FormData(); form_data.append('lecturer', this.state.lecturer); form_data.append('module', this.state.module); form_data.append('video', this.state.video); form_data.append('date', this.state.date); let url = 'http://127.0.0.1:8000/api/upload-lecture/'; fetch(url, { method: 'POST', body: form_data }).then(response => console.log(response)).catch(error => console.log(error)) }; } So after running method1 I checked the API logs and this is what I found [*] Error: {'video': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]} So I then attempted using another method, that is first using the JavaScript FileReader before I change the state of my video Code Below: This is the second way in which I tried to handle … -
Django - Post a List of Primary Keys and use their Values to Export Multiple CSV files
I have a TableView where a user can select 1 to X number of rows in the table. I use some jquery to collect primary keys for the selected rows and send these values back to the view with a form POST. I would like to export these PKs to seperate csv files - the workflow requires one CSV for each PK. I have CSV export working with a single PK to CSV, but exporting a list of PKs to seperate CSVs is not working, nothing is exported. I'm using the django-import-export package to customize the formatting of the csv. There a huge number of fields exporting, so I will try to post only the relevant code from the view. this code works for a single CSV export when it is called from its own url path: def export_csv(request, pk): slatedoc_resource = SlateDocResource() queryset = SlateDoc.objects.filter(pk=pk) dataset = slatedoc_resource.export(queryset) item = SlateDoc.objects.get(pk=pk) filename = f"{item.int_house_num}.csv" response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = f'attachment; filename={filename}' return response When I post a list of PKs from the TableView, the post() method will iterate over the PKs and send each one to the export_csv() function shown above. but no CSV files are ever exported. … -
The 'poster' attribute has no file associated with it
I keep getting this error every time I try to load my home page. This is the error I'm getting from chrome debugger: The 'poster' attribute has no file associated with it. 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Episode One</title> 7 {% load static %} 8 <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> 9 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> 10 </head> 11 <body> During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred Here is my models.py: class Pilot(models.Model): title = models.CharField(max_length=200) description = models.TextField() count = models.IntegerField() writer = models.CharField(max_length=200) year = models.IntegerField() script = models.FileField(blank=True, null=True, upload_to="scripts") poster = models.ImageField(blank=True, null=True, upload_to="posters") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) My urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('script_app.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My settings.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] I can't figure out what is tripping up. Can anyone tell me what is wrong?!!!! -
Returning Response directly from an internal function in django rest framework
I have a view that calls the other functions. Now based on different scenarios, the function has to return some error messages to the user. But if use return in that internal function, view always returns a "200 OK" until an exception has been raised. Below is a sample code - class BranchViewSet(BaseViewSet): serializer_class = BranchSerializer def create(self, request, *args, **kwargs): branch = super().create(request, *args, **kwargs) createBranchAdmin(branch.data) response = Response(branch.data, status=status.HTTP_201_CREATED) return response def createBranchAdmin(data): schema = Branch.objects.filter(BranchId=data['BranchId'])[0] name = schema.contactPerson phone = schema.phoneNumber existingUser = User.objects.filter(phone=phone) if existingUser: response = Response("User Already Exists!", status=status.HTTP_400_BAD_REQUEST) return response If a user already exists, I want to send this 400 Error to the user, but I get 201, even when the user exists. How to send this response to user directly from here? -
Django Guardian assign per object from existing group permission
I'm currently working on a project. In my project, there is a model called Room which includes some custom permissions. class Room(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # other fields ... class Meta: permissions = [ ('open_room', _('Can open room')), ('close_room', _('Can close room')), ] So, I have several roles for each permission level, including Owner (can anything), Staff (Can open and close room), and Reader (read only). The role will be created for group permissions. I want to create 3 template group permissions for these roles which can be used repeatedly. And if there are additional permissions for one of the groups above, automatically all groups associated with that role will get new permissions. My question is how can I do this? What I'm doing right now : When the user creates a new room, the system will create 3 new groups (owner, staff, reader) for the current room. The system names the group using the uuid prefix, 'Owner Room - uuid_room', 'Staff Room - uuid-room', ... The user who creates the room will be directly assigned to the owner group. Big thanks for you guys who read or answer my question. -
(Django) Saving a Custom User Model in Django Form Wizard
I am having trouble creating a multi-step registration page for users. So far, I have a custom user model called Account to which I have added some fields that affect other things within my project. The model works fine when I just use a single-step registration form. However, once I transitioned to a multi-step registration form (with Django Form Wizard) and separated the basic registration (email, username, password) from the other fields, I started encountering some difficulty. Reading the Django Form Wizard documentation doesn't help much. I also want to note I am creating another model (which has my custom user model as a Foreign Key) upon registration. Here is my code: forms.py class RegisterForm1(UserCreationForm): email = forms.EmailField() class Meta: model = Account fields = ["username", "email", "password1", "password2", ] help_texts = { 'username': None, 'password1': None, 'password2': None, } def __init__(self, *args, **kwargs): super(RegisterForm1, self).__init__(*args, **kwargs) self.fields['password1'].help_text = '' self.fields['password2'].help_text = '' class RegisterForm2(forms.ModelForm): class Meta: model = Account fields = ["int_field", "char_field", ] def __init__(self, *args, **kwargs): super(RegisterForm2, self).__init__(*args, **kwargs) views.py class register_new(SessionWizardView): template_name = "register/register.html" form_list = [RegisterForm1, RegisterForm2] def done(self, form_list, form_dict, **kwargs): form1 = RegisterForm1(self.request.POST) form2 = RegisterForm2(self.request.POST) if form1.is_valid() and form2.is_valid(): username = self.request.POST['username'] … -
How can I fix this searchbar error in django?
I'm trying to create a searchbar in my blog in python, but I'm receiving the following error: Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/article/(?P[0-9]+)$'] and I'm not sure why, so here's the code so you guys can see what's going on here: Traceback Traceback (most recent call last): File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\snin2\Desktop\basura\lapagina\app1\views.py", line 187, in searchbar return render(request, 'app1/search.html', {'query':query, 'results':results}) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line … -
Override Django Forms's Meta Classes
ContactForm is a common form in my app being used multiple times. I already have a Foreign Key of Contact Model in Guardian table.So the accepted answer from the solution works for me. But its making bit complex to write entire form again for below ContactForm fields when I have to reuse. So kept ContactForm separate to make it reusable. But still sometimes few fields are optional from the ContactForm, so not able to reuse same ContactForm again. class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ("address", "city", "district", "state", "country", "pincode", "phone1", "phone2", "is_emergency") Is there anyway to override Meta class by inheriting ContactForm in to the GuardianForm such as: class GuardianForm(forms.ModelForm, ContactForm): #obviously this will not work first_name = forms.CharField(max_length=30, required=False, label = "Parent's First Name") last_name = forms.CharField(max_length=30, required=False, label = "Parent's last Name") # Other Fields ... class Meta: model = Guardian fields = ('passport_number', 'pan_number', 'annual_income', 'phone1', 'phone2', 'is_emergency',) # Only 3 Fields of `ContactForm` -
How to get current logged in user in django with a custom abstract user
I'm trying to get the user which is actively making a post request to my api. I am using this to associate a posting with the user that makes it. However, when I make a post, it always returns Anonymous User. I am able to authenticate, sign up, and login properly. Is there any other way I could go about this? I am using django allauth to authenticate with email I have the following User model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=78) full_name = models.CharField(max_length=50) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return(self.email) The following is my Listing model: class Listing(models.Model): listingId = models.IntegerField(max_length=5) streetAddress = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=120) zipCode = models.IntegerField(max_length=5) price = models.IntegerField(max_length=6) deposit = models.IntegerField(max_length=6, default=0) description = models.TextField() rooms = models.IntegerField(max_length=2) bathrooms = models.IntegerField(max_length=2) rentalType = models.IntegerField(choices=RentalType.choices(), default=RentalType.HOUSE) amenities = models.TextField() listingUser = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='listings', on_delete=models.CASCADE, null=True) dateAvailable = models.DateTimeField(default=datetime.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.streetAddress And my views.py for the Listing model class ListingViewSet(viewsets.ModelViewSet): queryset = Listing.objects.all() serializer_class = ListingSerializer def perform_create(self, serializer): custom = settings.AUTH_USER_MODEL user = get_user_model() … -
Django model class __new__, what are the correct parameters to pass to super().__new__?
What are the correct parameters to pass to super().__new__ when I implement __new__ in a Django Model class? Most Django model classes do not need a custom __new__ constructor, but I'm implementing one (for purposes that I think are not relevant to this question). The Python documentation for the constructor method, __new__ is unclear about exactly what parameters must be passed. It says that the method: […] takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of new() should be the new object instance (usually an instance of cls). Typical implementations create a new instance of the class by invoking the superclass’s new() method using super().new(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it. That implies that a “typical” __new__ implementation should: def __new__(cls, *args, **kwargs): instance = super().__new__(cls, *args, **kwargs) do_some_customisation_of(instance) return instance When I try to do this on a Django model class: class LoremIpsum(django.db.models.Model): id = django.db.models.IntegerField(primary_key=True, …) dolor = django.db.models.FileField(…) def __new__(cls, *args, **kwargs): instance = super().__new__(cls, *args, **kwargs) do_some_customisation_of(instance.dolor) return instance Python raises a TypeError … -
How do you get unique user data for each user in a Django Web App
I'm creating a WebApp with Django as a personal project. This app tracks hiking challenges and gets the weather from a weather database with an API. My problem is currently with creating a database structure that will be a good design and expandable in the future. Currently, I have two Tables. (Django Models) class Mountain(models.Model): mnt_name = models.CharField(max_length=100) latitude = models.FloatField() longitude = models.FloatField() elevation = models.IntegerField(default=0) distance = models.IntegerField(default=0) users_completed = models.ManyToManyField(User) # Commented from code to prevent issues # date_done = models.DateTimeField(blank=True, null=True, default=None) def __str__(self): return self.mnt_name class Challenge(models.Model): challenge_name = models.CharField(max_length=101) mountains = models.ManyToManyField(Mountain) def __str__(self): return self.challenge_name I have some of the functionality I was looking for. I can loop through the list of users_completed and compare them against the currently logged in user and if the user is in the list update the completed status. But That isn't a good solution because I cant have user-specific dates completed among other reasons. Intuitively I thought the best way to go about fixing this issue is to add a copy for each challenge to each user profile so the user can have user-specific data such as the completion status and the date completed. But I'm not … -
How to set-up local server with Django
Recently, I'm working with Django to implement LOCAL web server. (For some reasons, it should be locally run) I've implemented the features and now I'd like to deploy this project. i.e. Make my web server start at PC start up. How could I do it? In some related Q&A, the answers said it is very risk approach that run python3 manage.py runserver X.X.X.X:YYYY as a background process. What is the safe approach to deploy my LOCAL server project? -
Django: Form.is_valid() keeps returning false
<div class="form-group col-md-3 col-md-offset-7 align-center p-2"> <form action="{{request.build_absolute_uri}}" method="post"> {% csrf_token %} {% for field in form %} <div class="row"> <label for="{{field.name}}">{{field.name|title}}</label> <input required type="text" id="{{field.name}}" value="{{field.value}}" name="{{field.name}}" placeholder="{{field.name}}" class="text-center mb-2 form-control form-control-sm"> </div> {% endfor %} <div class="row"> <button type="submit" class="btn col-12 btn-success">{% if request.session.language == 'lt' %} Išsaugoti {% elif request.session.language == 'en' %} Save Changes {% elif request.session.language == 'rus' %} логин {% endif %}</button> </div> </form> </div> This is how I render the form: if request.method == 'GET': form = UsersForm() return render(request, 'service_desk/ticket_list_edit.html', {'form': form}) if request.method == 'POST': form = UsersForm(request.POST) if form.is_valid(): form.save() return JsonResponse({'test': "we maybe getting somewhere"}) else: return JsonResponse({'test': "keep working"}) I don't really know what's the problem, it's my first time using form.is_valid() function. I'm doing remote database management, so I have all the fields in the front-end ready to be configured, and after trying using the 'POST' method to post the new stuff from front-end, I keep getting the same false return from is_valid()