Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a junction table in SQLite
I tried to find a solution on the internet but found just one tutorial which didn't help me that much. So here's my problem: I have a database that stores recipes but in different tables. E.g. one stores the title and the id, another stores the different preparations with the id, and the last one stores the ingredients and also each id. And to use it in Django properly I think I have to create a junction table, so I can use the database in Django from one model. I think I know how to create a junction table but I have no idea how to express on the one hand the OneToMany-relationship and on the other hand the ManyToMany-relationship(ingredients). So, I hope that you can either tell me another way of using it in Django right or you can help me creating the junction table -
Why is my css in Django app gets altered when I deploy my app on Heroku
I have created a website using Django and deployed it using Heroku..The problem is that size of divs and text which I have specified in my css files gets increased..On the other hand when I run the project on localhost the sizes and margins remain what I want..Why is this difference in size between localhost and actual website taking place? This is the link of my website -
Django Rest Framework - how to deal with data counting?
I have django app with django rest framework, that shows data from one table. It's very simple, when I enter url: http://127.0.0.1:8000/api/data/28/ it shows data that has dataset_id set to 28. However with a large amount of data it takes long time - even I can get 504. I looked into sql queries and found out, that there is this query: SELECT COUNT(*) AS "__count" FROM "my_table" WHERE "my_table"."dataset_id" = 28 that takes most of a time (like 50 sec), and second query, that actualy loades data: SELECT "my_table"."id", "my_table"."dataset_id", "my_table"."timestamp", "my_table"."data", FROM "my_table" WHERE "my_table"."dataset_id" = 28 ORDER BY "my_table"."timestamp" DESC LIMIT 25 and this query takes only 7 sec. Do you have any idea how to optimalize this? My idea is to somehow skip the first query, but still I need to know how many pages of data I have (just to not look blindly and get 404), so I don't know if it can be completely omitted. -
How to validate a django modelform if the form has some other fields
I have made a django model form but the problem is in my logic I am using something else and now I want to figure out a way to validate it by either defining a Meta class and choosing the fields that I want to display to the user but of course this won't validate the form. Now I want to know if there is a way to validate the form without touching the models and pass the data required for the logic and after take care of the information needed for the data of the model to be save Here is the models: from django.db import models from django.db import models from django.contrib.auth.models import User # Create your models here. class RoomCategory(models.Model): name = models.CharField(max_length=59) price = models.IntegerField() beds = models.PositiveIntegerField() capacity = models.PositiveIntegerField() size = models.CharField(max_length=59) def __str__(self): return self.name class Room(models.Model): room_number = models.CharField(max_length=60) room_category = models.ForeignKey(RoomCategory, on_delete=models.CASCADE) def __str__(self): return f"The room {self.room_number} {self.room_category} has a maximum of {self.room_category.capacity} person and cost {self.room_category.price}/night " class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(RoomCategory, on_delete=models.CASCADE) check_in = models.DateField() check_out = models.DateField() adults = models.PositiveSmallIntegerField() children = models.PositiveSmallIntegerField() def __str__(self): return f"{self.customer} has booked for {self.room} from {self.check_in} … -
subprocess.call nohup & - doesn't run process in background
I have a function (Django admin) that runs Scrapy spider. The function works correctly. What I'm trying to do now is to make it non-blocking. This works as expected - I need to wait for the finish of SH SCRIPT. So basically I click on this action and browser is waiting for the end of crawling. subprocess.call([settings.CRAWL_SH_ABS_PATH, "db_profiles_spider", "ids", ids]) I want it to be non-blocking so the browser refreshes immediately. I tried this: subprocess.call(["nohup",settings.CRAWL_SH_ABS_PATH, "db_profiles_spider", "ids", ids, '&']) But it seems to be blocking and browser waits for the response. Why? How can I make it work? -
How to handle dynamically added variables in Django template
I am attempting to build a Django template that dynamically handles variables that may or may not exist. Here is the type of pattern I am using: {% block unsubscribe %} {% if unsubscribe_uuid is not None %} <a href="http://www.example.com/core/unsubscribe/{{ unsubscribe_uuid }}/" style=" font-size: .9em; color: rgba(255, 255, 255, 0.5);"> unsubscribe</a> | {% endif %} {% endblock %} This throws an error/exception/warning: django.template.base.VariableDoesNotExist: Failed lookup for key [unsubscribe_uuid] I've also tried checking with this line to check for the variable: {% if unsubscribe_uuid %} How can I check for variables in my template without throwing this error if they don't exists? -
How to update an arrayfield column in Django?
I have a column called errors in my table that is defined as ArrayField(models.IntegerField(default=0), default=list, null=True). The following is the updation that I'm doing to my table in a for loop over 100 iterations. testcase = Table1.objects.filter(ID=id,serialno ='1234', condition='False').select_for_update().update(condition='True', errors=iter_val) iter_val is an integer which is returned from the number of iterations in the for loop. I need the errors field to have an entry like [3,45,67,68,70,89]. But .update doesn't seem to append the integers to the array. How do I append the values to the arrayfield over a loop? -
why Django nginx server is not working when no requests are sent?
I don't know much about the nginx server. So, I have a doubt why it is not working as localserver used while making a django project. I have googled about this issue in different ways but it is of no use. So, kindly explain this to me. -
Namespacing DateArchiveView Url Django
Im trying to reference a date_based url archives such as WeekArchiveView,MonthArchiveView.When i hardcode the url its working ,but when i reference i have an error.I know there something am missing during referecing. VIEWS class MonthlySales(MonthArchiveView): queryset=Product.objects.all() date_field='date_purchased' allow_empty=True; class WeeklySales(WeekArchiveView): queryset=Product.objects.all() date_field='date_purchased' week_format ='%W' allow_empty=True; URLS url(r'^(?P<year>[0-9]{4})/week/(?P<week>[0-9]+)/$',views.WeeklySales.as_view(),name="weekly-sales"), url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/$',views.MonthlySales.as_view(),name="monthly-sales"), REFERENCING IN HTML <a class="nav-link" href="{% url 'pos:monthly-sales'%}">Monthly sales</a> <a class="nav-link" href="{% url 'pos:weekly-sales'%}">Weekly Sales</a> Any assistance will be appreciated. Thankyou in advance -
The view user.views.profile didn't return an HttpResponse object. It returned None instead
views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import UpdateUserForms, ProfileUpdateForm from django.contrib import messages # Create your views here. @login_required def profile(request): if request.method == 'POST': u_form = UpdateUserForms(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account is updated!') return redirect('profile') else: u_form = UpdateUserForms(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'profile.html', context) The view user.views.profile didn't return an HttpResponse object. It returned None instead. this error is occuring -
Django Graphql middleware decode token
In my project I use Django and GraphQl for building API. The user will be authenticated by API Gateway in AWS, and send to backend an JWT token, with uuid username body, included in the request headers. I need to decode that token and get an username value, that will be next used in the resolvers. I planned to use something similar as G object in Flask or something similar using Rack (Djangos middleware) https://github.com/RenoFi/rack-graphql#example-using-context-handler-for-jwt-authentication but I'm struggling how to do it in Django. Do you have any ideas? -
Annotate queryset with count of elements from another queryset
I have two models connected to User model: class Comment: author = FK(User) ... class CourseMembership: user = FK(User, unique=True) ... I want to annotate each item in CourseMembership.objects.all() with number of comments created by corresponding User. I tried something like this: course_comments = Comment.objects.filter(author=OuterRef("user")) cm = CourseMembership.objects.annotate(comments_count=Count(Subquery(course_question_comments))) but I receive only errors. Can someone help me? -
Same databses for ruby and django
I have same database for ruby and django. Ruby stores user data using bycrypt algorithm(i.e using devise gem): ex : $2a$10$5JhrmU73vXEJWyoBQqYaKeM6a5KwxTfTrfARJmyyl.E8Tir3Q0nlG But to authenticate same user in django,my django bicrypt algorithm should also output same text that is: $2a$10$5JhrmU73vXEJWyoBQqYaKeM6a5KwxTfTrfARJmyyl.E8Tir3Q0nlG. How to do this? It's exactly opposite of this question: Migrate django users to rails -
when a user creates an account,how do i convert the email to all lower case before saving to models?
class GetLoanRepaymentHistoryView(ListAPIView): """Get all loan repayment history.""" serializer_class = LoanRepaymentSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, AdminDashboardPermission,) class GetLoanRepaymentHistoryView(ListAPIView): """Get all loan repayment history.""" List item serializer_class = LoanRepaymentSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, AdminDashboardPermission,) def get_queryset(self): try: loan = Loan.objects.get(id=self.kwargs.get('id')) except Loan.DoesNotExist: return Response({'non_field_errors': ['Loan does not exist']}, status=status.HTTP_404_NOT_FOUND) return LoanRepayment.objects.filter(loan=loan) -
How to construct a Django model that is purely made from other models related by ticker?
How to make up a "parent" model that is solely composed of other models ? I am currently thinking to use foreignkey relationships but I don't believe this is the right way to do so. class BalanceSheet(models.Model): ticker = models.ForeignKey( Stock, on_delete=models.CASCADE, related_name="balance_sheets" ) assets = models.ForeignKey(Assets, on_delete=models.CASCADE) liab_and_stockholders_equity = models.ForeignKey(LiabAndStockholdersEquity, on_delete=models.CASCADE) def __str__(self): return f"{self.ticker} Balance Sheet" class Assets(model.Model): ticker = models.ForeignKey( Stock, on_delete=models.CASCADE, related_name="assets") balance_sheet = ???????????????????????????? class Assets(model.Model): ticker = models.ForeignKey( Stock, on_delete=models.CASCADE, related_name="liab_and_stockholders_equity") balance_sheet = ?????????????????????????? -
CV2.VideoCapture(0) is not working for Django+openCV deployment on AWS EC2
I am building face recognition web application using Django and opencv. I have trained ML models. In my development stage i am able to access webcam with cv2.VideoCapture (0). But while i am deployed on AWS. I can't able to get any response from cv2.VideoCapture() . Is there anyway i can get access to user's device webcam when someone visit my website? -
How can i package a fully developed django project and make it installable
I have a fully developed Django python projects that I can install on windows using xampp or wamp and I have a custom browser developed for it using pyqt5, but I want to automate the configuration of the Django app with the following process: Create a .exe file in which a user can click and its will perform the following function in the background download the code from Github using git clone check if python is installed on the system if yes install virtualenv create a virtualenv and install the project requirement file run python manage.py migrate run python manage.py collect static -
Setting up same env variable with different values in different supervisord process
I have two django projects running in same vm, but both apps got crontab requirements. So i created separate worker and beat conf file supervisord place. But i need to export DJANGO_SETTINGS_MODULE value to different in different process. Like below 1.[supervisord] environment=DJANGO_SETTINGS_MODULE='***.settings.azure' [program:coursecelerybeat] directory=/home/***/***/ command=/home/***/***/bin/celery beat --app=***.celery --loglevel=INFO 2.[supervisord] environment=DJANGO_SETTINGS_MODULE='***.settings.azure' [program:usercelerybeat] directory=/home/***/***/ command=/home/***/***/bin/celery beat --app=***.celery --loglevel=INFO In the place ***, i need to add concerned project folder name. But if i set, it's added permanantely. So it's not working as expected. The same problem happened while gunicorn setup time, but in gunicorn we have environmentfile option. That resolved my problem. But in my supervisord, i'm not able to find anything like that. -
Why Heroku won't start the server?
I uploaded the application to heroku, did the migration but when I run heroku open it gives me an error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I checked the log and here is the answer 2020-08-30T14:00:17.028467+00:00 app[web.1]: ModuleNotFoundError: No module named 'myfist' 2020-08-30T14:00:17.028793+00:00 app[web.1]: [2020-08-30 14:00:17 +0000] [11] [INFO] Worker exiting (pid: 11) 2020-08-30T14:00:17.135517+00:00 app[web.1]: [2020-08-30 14:00:17 +0000] [4] [INFO] Shutting down: Master 2020-08-30T14:00:17.135762+00:00 app[web.1]: [2020-08-30 14:00:17 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-08-30T14:00:17.263710+00:00 heroku[web.1]: Process exited with status 3 2020-08-30T14:00:17.339367+00:00 heroku[web.1]: State changed from starting to crashed 2020-08-30T14:00:18.000000+00:00 app[api]: Build succeeded 2020-08-30T14:01:05.766286+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sheltered-reef-33234.herokuapp.com request_id=0c2820c9-774c-4b3d-86c4-c53e2531f986 fwd="188.163.103.167" dyno= connect= service= status=503 bytes= protocol=https 2020-08-30T14:01:06.363461+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sheltered-reef-33234.herokuapp.com request_id=b16b581b-fce7-4dce-bfdd-8707f4ec2433 fwd="188.163.103.167" dyno= connect= service= status=503 bytes= protocol=https But when I run on the local server everything works Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 30, 2020 - 19:01:48 Django version 3.0.3, using settings 'myfirst.settings' Starting development server … -
How to display data from celery task into django template
I am working on a django project. In the project, I am scraping some data from a website and storing the results into a django model. I want to now display this data in a django template as and when it is saved in the model. this is my code so far mainapp/views.py from django.shortcuts import render from .tasks import get_website from .models import Articles def index(request): if request.method == 'POST': website = request.POST.get('website') title = request.POST['title'] author = request.POST['author'] publish_date = request.POST['publish_date'] get_website.delay(website, title, author, publish_date) return render(request, 'output.html') return render(request, 'index.html') def output(request): return render(request, 'output.html') in the index page, I have a form which when submitted starts the scraping process through the celery task get_website(). mainapp/tasks.py @shared_task def get_website(website, title, author, publish_date): ... return save_function(article_list) @shared_task(serializer='json') def save_function(article_list): print('saving extracted data') new_count = 0 for article in article_list: try: new_article = Articles( Title = article['Title'], Link = article['Link'], Website = article['Website'], Author = article['Author'], Publish_date = article['Publish_date'], ) new_count += 1 new_article.save() except Exception as e: print(e) break return print('finished') All of the scraped data is stored in a list article_list and is passed to save_function() to save the data into the django model Articles. I want … -
Incorrect padding
If I would like to go my site and type any of these: www.example.org, example.org, http://example.org, https://example.org, example... I have no problem transferring to my site using internet explorer, google, opera, edge... But, if I open Google (sometimes on the phones using Google too) and type www.example.org, it gives me following: Error at /my_site/ Incorrect padding Request Method: GET Request URL: http://www.example.org/my_site/ Django Version: 3.1 Exception Type: Error Exception Value: Incorrect padding Exception Location: /usr/local/lib/python3.8/base64.py, line 87, in b64decode Python Executable: /home/mysiteorg/pro/my_project/bin/python3 Python Version: 3.8.5 I have no idea what to do with it... Any help, please! Thank you!!! -
found problem Django data transfer by render request to template
I have tried a several times but can't find anything wrong. Here is my code. [This is from views.py][1] [1]: https://i.stack.imgur.com/l0d4a.png This is from html file. -
query ForeignKey of model
**I want get all orders of customer whose id = 3 ** ---------------------------------------------------------------- class customer(models.Model): name = models.CharField(max_length=200,null= True) phone = models.CharField(max_length=200,null= True) email = models.CharField(max_length=200,null= True) date_created = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name class order(models.Model): STATUS = ( ('pending','pending'), ('out for delivery','out for delivery'), ('deliveried','deliveried') ) date_created = models.DateTimeField(auto_now_add=True,null=True) status = models.CharField(max_length = 200 , null=True,choices=STATUS) customer= models.ForeignKey(customer,null=True,on_delete=models.SET_NULL) product = models.ForeignKey(product,null=True,on_delete=models.SET_NULL) -
Add custom field to Django Admin authentication form
I'm Building an application where the auth process has three fields. subdomain username password Each subdomain defines an isolated space and the username is unique only inside its subdomain For example: the subdomain foo.bar.com has the user jhon_doe with the password secret. It may exists another jhon_doe but in other subdomain. So ... I've created a custom backend authentication and it works well. The problem is that the login Django Admin form have username and password fields by default. I would like to implement a custom Django Admin login form with subdomain username and password fields. -
Using Google docs api with django
Im trying to integrate goofle docs api with django app so that uploaded files can be edited and new files can be created.But im not able to integrate the same .Please Help!