Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Deleted database in development and then created a brand new one, will it cause an error when I push to production?
Following steps in Scenario 1 in the following document https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html I deleted my database in development environment and created a brand new one. Things are working fine in development, however, when I push to production I get the following error: django.db.utils.ProgrammingError: column "shop_id" of relation "subscribers_subscriber" already exists Should I have not deleted my database in dev, given I already have a prod environment, or is deleting db in dev perfectly fine, and will have no effect on prod environment? And that something else is causing the error? Note: I am using a postgresql database -
Django Model Form Validation not validating
Hey I am busy with Django forms working on custom validation etc, so when I test whether this validation is working it does not work I tried watching videos so to know where I am going wrong but I personally do not see the flaw. I did a password validation and it does not raise the validation error to me even when I write two different passwords. Code Below: models.py class UserAccounts(models.Model): name = models.CharField(max_length=100, blank=False, null=False) last_name = models.CharField(max_length=100, blank=True, null=False) phone_number = PhoneNumberField(unique=True) email = models.EmailField(blank=False, null=False, unique=True) password = models.CharField(max_length=100, blank=False, null=False) verify_password = models.CharField(max_length=100, blank=True) def __str__(self): return self.name def clean_password(self): passwd = self.cleaned_data_get('password') v_passwd = self.cleaned_data_get('verify_password') if passwd != v_passwd: raise ValidationError('Passwords do not match') return passwd Code Below: forms.py class UserAccountsForm(ModelForm): class Meta: model = UserAccounts fields = '__all__' widgets = { 'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'}), 'last_name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'}), 'phone_number': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number'}), 'email': forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'}), 'password': forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'}), 'verify_password': forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Verify Password'}) } -
I completed the tutorial on creating a chatroom using Django Channels but I don't know how to add a username
So, if I can at all avoid it, I don't want to go through the hassle of making a username/password for anyone who wants to use this chatroom. This is a school project, not a commercial one, so it doesn't need that kind of security. What I want is for the user, when they enter the chatroom, to give their name and have that be used. What can I add on to this tutorial to make that happen? I am a complete beginner. This is the tutorial I used. I completed only up to part 2 as I did not wish to do the async. My code is almost identical to the tutorial. https://channels.readthedocs.io/en/latest/tutorial/part_1.html -
Dynamic filtering in Django 3
I'm new in Django. I'm searching ways to create dynamic filtering for my project. I can't find an easy way of doing it. I need to be able to sort, and filter for 5 different categories. And search among these results. I am using genericListView. Could anyone please help me by giving recommendations and example snippets for easy understanding? -
How can I transfer Django session authentication to my Vue frontend?
My app uses Django and rest framework backend, Vue frontend. I would like users to use session authentication and login via Django's allauth, with its email verification and password reset support. On login, users are redirected to a Vue component, and I can put the CSRF token into request headers. I need to get user object (or user ID) into my Vuex store at this point. Are these my choices, or are there others? give up using session authentication and use JWT put some kind of session data or token into localstorage that Vue could then retrieve. (How could I do this?) somehow get user ID from CSRF token Any advice appreciated. -
Can't get indexing for Header Column with Pandas
I am trying to resonate excel file with Panda's data representation in Django templates. I've tried quite a few things but I can't get header columns indexed as 1. Pandas starts indexing below the header columns. If will be great help if someone can guide me. Below is the code I am trying to resonate with Excel sheet exactly. def home(request): template = 'home.html' form = ExcelUpload(request.POST or None, request.FILES) if request.method == 'POST': if form.is_valid(): excelfile = ExcelFileUpload(uploaded_file = request.FILES['uploaded_file']) excelfile.save() data = pd.read_excel(excelfile.uploaded_file.path, header=None) new_header = data.iloc[0] data = data[1:] data.columns = new_header data_to_html = data.to_html return render(request, template, {'form':form, 'data_to_html':data_to_html}) else: form = ExcelUpload() return render(request, template, {'form': form}) My excel file shows 20 entries indexed in the but when I parse it to web it shows me 19 entries indexed like this . I need help to convert headers into index 1 so my excel file and web sheet resonates. Thanks. -
Django inlineformset_factory not rendering extra fields
i am using Django inlineformset_factory with extra=2 but everytime it renders only one form. here are the codes: models.py class Education(models.Model): DEGREE_TYPE = (("UG", "UG"), ("PG", "PG"), ("PHD", "PHD")) user = models.OneToOneField(User, null=False, blank=False, on_delete=models.CASCADE) institute = models.CharField(max_length=255, null=True, blank=True) degree_type = models.CharField(max_length=3, null=True, blank=True, choices=DEGREE_TYPE) degree = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return str(self.user) forms.py class EducationForm(forms.ModelForm): class Meta: model = Education fields = "__all__" exclude = ["user"] views.py @login_required def profile_page(request, id): user = get_object_or_404(User, id=id) EducationInlineFormset = inlineformset_factory(User, Education, fields=("institute", "degree_type", "degree"), extra=2) if request.method == "POST": education_formset_data = EducationInlineFormset(request.POST, instance=user) if education_formset_data.is_valid(): education_formset_data.save() messages.success(request, "Education details updated successfully!") return redirect(reverse('profile', kwargs={"id": id})) education_formset = EducationInlineFormset(instance=user) payload = {"education_formset": education_formset} return render(request, "profile.html", payload) form html <form method="POST" action=""> {% csrf_token %} <div class="form-scroll"> {{ education_formset.management_form }} {% for education_form in education_formset %} <div class="card"> <div class="card-body"> {{ education_form }} <hr> </div> </div> {% endfor %} </div> <div class="submit-section"> <button class="btn btn-primary submit-btn">Submit</button> </div> </form> so far everything looks fine to me, but still it's not working. please suggest me a solution, what is going wrong here! btw i have some others models also that are in OneToOne relationship with User model, can that be the problem? -
I am trying to redirect my in my django app but its giving me NoReverseMatch error
I expect code to redirect to url with name=home. But I am getting an error. code snippet from my views.py: def signup(request): if request.method=='POST': form = Signup(request.POST) if form.is_valid(): name = form.cleaned_data['username'] email = form.cleaned_data['email'] new_user = User(name=name, email=email) new_user.save() return redirect('home') code snippet from my urls.py: urlpatterns = [ path('', views.home, name='home')] Error I am getting is: NoReverseMatch at /signup/ Reverse for 'home' not found. 'home' is not a valid view function or pattern name. -
CSRF TOKEN issue when interacting with apis
So the authentication and APIs were all working but then I took some time to integrate Django and react a little more by following the tutorial at http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/. when I got the dev server connected correctly using django-webpack-loader 0.70.0 and webpack-bundle-tracke 0.43.0, all of the access to the server started to fail due to " CSRF token missing or incorrect." I tried adding the csrf token to the default headers in Axios but it still didn't allow the response to go through. and the thing is that even requests from postman began to fail as well. I would appreciate any ideas. Thank you in advance. index.js axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.baseURL = config.baseURLApi; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.headers.common["Content-Type"] = "application/json"; const token = localStorage.getItem("token"); if (token) { axios.defaults.headers.common["Authorization"] = `Token ${token}`; } Django settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), # 'DEFAULT_RENDERER_CLASSES': ( # 'rest_framework.renderers.JSONRenderer', # ) } CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', "http://localhost:3000", ] CSRF_TRUSTED_ORIGINS = [ 'localhost:3000', 'localhost:8000' ] CORS_ALLOW_METHODS = list(default_methods) + [ 'POKE', ] CORS_URLS_REGEX = r'^/api.*' browser network info Request URL: http://localhost:8000/api/auth/login Request Method: POST Status Code: 403 Forbidden Remote Address: [::1]:8000 Referrer Policy: no-referrer-when-downgrade Access-Control-Allow-Origin: * Content-Length: 2864 Content-Type: text/html Date: Sun, 26 Jul 2020 … -
Django Queryset: Group by month
I am trying count all my id and group by month in Django. My id field is a Datetime has the format "2020-07-26 22:08:55.747424", harder than I thought. Been looking at other examples as well without any luck. Any suggestions? My current Queryset while experimenting myquery = alldata.objects.all().filter(id__year="2020").annotate(date=TruncMonth('id'),).values(('month').annotate(total_entries=Count('id'))) Error message AttributeError at /page/ 'str' object has no attribute 'annotate' -
Static/CSS files issues in django
I am just new to django and after making a simple authentication forms for log in and logout.Everything is working perfectly but whenever i want to make some changes to the styles (CSS) it doent work. I have tried after changing the directory of static files but all in vain. Even if i remove all the code from CSS file the page still showing all the style related stuff. kindly suggest me what should i do? below i have attached the image of my all code and directories. -
How to resolve TypeError: __init__() got an unexpected keyword argument 'attrs' Django
Hello I am working on Django forms however I am getting this error TypeError: init() got an unexpected keyword argument 'attrs' So what I do not understand is I get the error only when I include the email and the two passwords fields and this really does not make sense to me hence I fail to fix this error can I please get help to understand what is actually happening here and what is causing this error. CODE BELOW: forms.py from django import forms from phonenumber_field.formfields import PhoneNumberField class UserAccount(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Surname'})) phone = PhoneNumberField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number'})) email = forms.CharField(widget=forms.EmailField(attrs={'class':'form-control', 'placeholder':'Email'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'})) verify_password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'verify password'})) I do not know if the views.py file and the html file will help fix this error please state and I shall gladly update the question -
Nginx does not serve static and media files for the Django application
i have spent a lot of time finding out what i did wrong. When i start server almost everything is working fine, but Nginx does not serve static and media files for the Django app. Please, i need your help! nginx.conf user nginx; worker_processes auto; events { worker_connections 1024; } http { server { listen 80; server_name localhost; access_log /var/log/nginx/example.log; location /static/ { root /nginx/static/; } location /media/ { root /nginx/media/; } location / { proxy_pass http://server:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } } docker-compose.prod.yml version: '3' services: nginx: build: context: ./ dockerfile: ./nginx/Dockerfile depends_on: - server ports: - 80:80 volumes: - ./server/media:/nginx/media server: build: context: ./ dockerfile: ./server/Dockerfile command: gunicorn config.wsgi -c ./config/gunicorn.py volumes: - ./server/media:/server/media ports: - "8000:8000" depends_on: - db environment: DEBUG: 'False' DATABASE_URL: 'postgres://postgres:@db:5432/postgres' BROKER_URL: 'amqp://user:password@rabbitmq:5672/my_vhost' db: image: postgres:11.2 environment: POSTGRES_DB: postgres POSTGRES_USER: postgres Dockerfile FROM python:3.7-slim AS server RUN mkdir /server WORKDIR /server COPY ./server/requirements.txt /server/ RUN pip install -r requirements.txt COPY ./server /server RUN python ./manage.py collectstatic --noinput ######################################### FROM nginx:1.13 RUN rm -v /etc/nginx/nginx.conf COPY ./nginx/nginx.conf /etc/nginx/ RUN mkdir /nginx COPY --from=server /server/staticfiles /nginx/static oooooooooooooooooooooooooooo Thank you for paying attention! oooooooooooooooooooooooooooo -
UnicodeDecodeError while deploying to Elastic Beanstalk
I have a Django application which it's deployed to Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I'm getting the error below when I try to update and re-deploy my application. Logged from file util.py, line 502 Traceback (most recent call last): File "/usr/lib64/python2.7/logging/__init__.py", line 891, in emit stream.write(fs % msg.encode("UTF-8")) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 89: ordinal not in range(128) I have tried the export LC_CTYPE=en_US.UTF-8 line but it doesn't work. How can I fix this issue? -
Refresh Django wizard form after browser's back button
I am using SessionWizardView from django-formtools project. I've noticed that after successfully passing all form checks and executing done() function, which redirects to completely different view, user can still hit browser Back button and re-fill form again. Isn't there any way to prevent that? I would assume that it would be some kind of session cleaning mechanism. But I cannot find any in documentation. -
Django grouping UI elements
I have a Django project where I am pulling back a list of tasks. These tasks could be for many projects. Task1: Project1 Task2: Project2 I really want to be able to group by project, so they all sit together, but the project names are input by the user, so I can't hardcode if statements. How could I approach this? -
how to upload zip files in Django
How to upload zip files in Django? because i want to fetch the uploaded file with axios. I have already converted file into zip file and want to POST the zip file or GET. def get(self, response): directories = os.path.commonprefix(['Zipped_file.zip']) response = HttpResponse( directories, content_type='application/zipfile') response['Content-Disposition'] = 'attachment; filename="Zipped_file.zip"' return response it downloads without any files inside the zip folder ! any help will be apreciated thank you :) -
Url doesnt run the proper view in pinax project blog
poblem mentioned at the end. so i installed pinax blog app and added to my installed app , migrated and set up all its dependencies. i then added it to the urlpatterns in my project : urlpatterns = [ path('admin/', admin.site.urls), url(r"^blog/", include("pinax.blog.urls", namespace="pinax_blog")), url(r"^ajax/images/", include("pinax.images.urls", namespace="pinax_images")), ] the urpatterns in pinax.blog.urls are : urlpatterns = [ url(r"^$", BlogIndexView.as_view(), name="blog"), url(r"^section/(?P<section>[-\w]+)/$", SectionIndexView.as_view(), name="blog_section"), url(r"^post/(?P<post_pk>\d+)/$", StaffPostDetailView.as_view(), name="blog_post_pk"), url(r"^post/(?P<post_secret_key>\w+)/$", SecretKeyPostDetailView.as_view(), name="blog_post_secret"), url(r"^feed/(?P<section>[-\w]+)/(?P<feed_type>[-\w]+)/$", blog_feed, name="blog_feed"), # authoring url(r"^manage/posts/$", ManagePostList.as_view(), name="manage_post_list"), url(r"^manage/posts/create/$", ManageCreatePost.as_view(), name="manage_post_create"), url(r"^manage/posts/(?P<post_pk>\d+)/update/$", ManageUpdatePost.as_view(), name="manage_post_update"), url(r"^manage/posts/(?P<post_pk>\d+)/delete/$", ManageDeletePost.as_view(), name="manage_post_delete"), url(r"^ajax/markdown/preview/$", ajax_preview, name="ajax_preview") ] the BlogIndexView: class BlogIndexView(ListView): model = Post template_name = "pinax/blog/blog_list.html" search_parameter = "q" paginate_by = settings.PINAX_BLOG_PAGINATE_BY def get_current_section(self): return "all" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ "current_section": self.get_current_section(), "search_term": self.search_term() }) return context def search_term(self): return self.request.GET.get(self.search_parameter) def search(self, posts): q = self.search_term() if q: posts = posts.filter( Q(title__icontains=q) | Q(teaser_html__icontains=q) | Q(content_html__icontains=q) ) return posts def get_queryset(self): blog = hookset.get_blog(**self.kwargs) qs = Post.objects.current().filter(blog=blog).select_related("section", "blog") return self.search(qs) Question: when i run sever and go to http://127.0.0.1:8000/blog/ the BlogIndexView should work according to first url pattern of pinax_blog's url pattern and the template_name = "pinax/blog/blog_list.html" should be loaded. but the template doesnt load a different template called site_base.html loads instead … -
Internal Server & Syntax Error while using fetch in Javascript
im very new to Javascript, Django & web development in general. Im following a cs50 web dev course by harvard and I have to design a front-end for an email client that makes API calls to send and receive emails. Ill get mail, send mail, and update emails by using an API that is written specifically for us. I need to send a GET request to /emails/ where is either inbox, sent, or archive, and it will return back (in JSON form) a list of all emails in that mailbox, in reverse chronological order. How to fetch, as instructed by the course: fetch('/emails/sent') .then(response => response.json()) .then(emails => { // Print emails console.log(emails); // ... do something else with emails ... }); I put this exact code in my .js file and it gives me these two errors: GET http://127.0.0.1:8000/emails/sent 500 (Internal Server Error) load_mailbox @ inbox.js:85 (anonymous) @ inbox.js:24 127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) load_mailbox @ inbox.js:87 (anonymous) @ inbox.js:6 What shows at the cmd: Is the issue at the timestamp of the model in django? I dont understand why. Internal Server Error: /emails/sent Traceback (most recent call last): … -
how to download 'gettext 0.21+' in windows
in Django doc, they said : Since string extraction is done by the xgettext command, only syntaxes supported by gettext are supported by Django. In particular, Python f-strings are not yet supported by xgettext, and JavaScript template strings need gettext 0.21+. I want to translate template strings in JS in Django project now, so I need to download gettext 0.21+. however I find the lasted version is 0.20. -
How to make fade in and out transition in javascript?
How can I make the transition below have fade in and out? Please bear with me as I'm not that great with javascript. I already tried some solutions online and none of them worked for me. I followed their instructions as best I can. I'm not sure if I messed up somewhere when I tried them. Anyway help is greatly appreciated! The javascript for this form is shown below function registerNext(){ document.querySelector(".first_name").style.display = "none"; document.querySelector(".last_name").style.display = "none"; document.querySelector(".email").style.display = "none"; document.querySelector(".password1").style.display = "none"; document.querySelector(".password2").style.display = "none"; document.querySelector(".student_number").style.display = "block"; document.querySelector(".graduation_year").style.display = "block"; document.querySelector(".degree").style.display = "block"; document.querySelector(".program").style.display = "block"; document.querySelector(".btn-next").style.display = "none"; document.querySelector(".btn-back").style.display = "inline"; document.querySelector(".btn-signup").style.display = "inline"; document.querySelector("form.register-form label").style.display = "block"; document.querySelector("legend.step-2").style.display = "block"; document.querySelector("legend.step-1").style.display = "none"; } function registerBack(){ document.querySelector(".first_name").style.display = "block"; document.querySelector(".last_name").style.display = "block"; document.querySelector(".email").style.display = "block"; document.querySelector(".password1").style.display = "block"; document.querySelector(".password2").style.display = "block"; document.querySelector(".student_number").style.display = "none"; document.querySelector(".graduation_year").style.display = "none"; document.querySelector(".degree").style.display = "none"; document.querySelector(".program").style.display = "none"; document.querySelector(".btn-next").style.display = "block"; document.querySelector(".btn-signup").style.display = "none"; document.querySelector(".btn-back").style.display = "none"; document.querySelector("form.register-form label").style.display = "none"; document.querySelector("legend.step-2").style.display = "none"; document.querySelector("legend.step-1").style.display = "block"; } The css for the form .first_name, .last_name, .email, .password1, .password2, legend.step-1{ display: block; } .student_number, .graduation_year, .degree, .program, form.register-form label, legend.step-2{ display: none; } button.btn-next{ display: block; margin-right: 0; margin-left: auto; animation: bounce; … -
keep getting type error unhashable type: 'dict' for Django
My urls.py: The Error message: The settings.py: -
how can i make number of objects of a particular model under one specific model in django 3.0
i want to attach a model called 'task' which comes with two attributes class Task(models.Model): task_name = models.CharField(default='Task Name' ,max_length = 100,) task_description = models.CharField(default='Task Description' ,max_length = 100,) to another model called branch class branch(models.Model): branch_name = models.CharField(default='Branch_Name' ,max_length = 100,) subject_1= models.CharField(max_length = 100,) subject_2= models.CharField(max_length = 100,) subject_3= models.CharField(max_length = 100,) in this , the working is simple in each branch there are number of subjects to study , under each subject there can be number of tasks. how can i build one efficient app which link the model 'task' to model 'branch'. so that i can create number of branches and in each branch there can be number of tasks under each subject,each task is differentiated from one another using field reference ' task_name' which comes under the model 'task' . -
flipping query in django
hi i want to make a reverse query , imagine i have these models how to make such query items__customer_returns__quantity__gte=1 class InvoiceModel(models.Model): customer = models.CharField(max_length=30) phone = models.CharField(max_length=15) product= models.ManyToManyField(Products,through='SelectQuantityModel') def __str__(self): return str(self.id) class SelectQuantityModel(models.Model): product= models.ForeignKey(Products, on_delete=models.CASCADE) items = models.ForeignKey(InvoiceModel,on_delete=models.CASCADE,default='',related_name='product') quantity= models.IntegerField() price = models.IntegerField() class ReturnInvoiceModel(models.Model): invoice_number = models.ForeignKey(InvoiceModel,on_delete=models.CASCADE,related_name='customer_returns') product = models.ManyToManyField(Products,through='SelectQuantityReturnModel') class SelectQuantityReturnModel(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE) item = models.ForeignKey(ReturnInvoiceModel,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.IntegerField() i need to go through SelectQuantityModel to SelectQuantityReturnModel to do some calculation : i tried this but doesnt work SelectQuantityModel.objects.filter(items__customer_returns__quantity__gte=1) items : from SelectQuantityModel customer_returns from ReturnInvoiceModel quantity from SelectQuantityReturnModel but it says customer_returns is an invalid field ? -
Using django in spyder
I couldn't find any documentation about how to use django in spyder. All of the users use django in VS Code. But I want to use django for web development in spyder. Isn't it possible? If anyone knows about it, please suggest me. Thank You.