Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Identical string in database is why now allowed
I'm currently working in Django and just reminded that professor said don't use same string in different models in same database because it may cause some problems. He said if you want to use it, make another model and use foreign key. But what's the reason we do not have to use identical string in one database? I implemented in two ways, one use another model with foreign key, and one just use same database using same string(but that field is not pk ofc). And it doesn't matter on both cases. So I tried to find why professor said like that, but couldn't find a reason. Is there anyone who can tell me the reason why I shouldn't use identical string in different object in same model? -
Deleting foreign key value
I have got a model that looks like that: coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) When I am trying to delete the coupon using this function: def remove_coupon(request): coupon = Order.objects.get( user=request.user, ordered=False) coupon.coupon.delete() return redirect("core:checkout") It deletes the coupon from Order model, but it also deletes the coupon in the Coupon model. I wanted to make it so it only deletes the value from Order and not from Coupon model. I have also tried on_delete=models.CASCADE , but my site crashes then. Where is the problem? -
how to copy rows from one table to other in django which meet a particular condition?
I want to copy all those fields which meet this condition '''Table1.objects.filter(post_home=True)''' ( where post_home is a boolean field in my Table1)to my other table Table2 which have the same fields as Table1 -
How to change title for the tab of User Add Page of Django admin?
I'm working on Django and wanted to change the default title for the tab of User Add Page of Django admin as marked in the pic : and my admin.py file is : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So what should be done to change it?? Thanks in advance!! -
How to use Enum in a model field as an argument type for a query or mutation in graphene django?
One of the model fields is choice eg. personType = (('Student','Student'),('Teacher','Teacher')) person_type = models.CharField(max_length=20, choices=personType) How can I use the same personType as an argument for a mutation? -
The correct way to use super(type, obj).save() with Django models
In the following code snippet, I have two models (MyObject and MyOption). class MyOption(object): obj = models.ForeignKey( MyObject, on_delete=models.CASCADE, related_name="options" ) defaultoptions = [{}, {}, ...] MyOption.save() is defined as such: def save(self, *args, **kwargs): isvalidated = self.validated() if isvalidated: super(self.__class__, self).save(*args, **kwargs) else: return None # Every object must have at least one corresponding MyOption # Create the default options if none are currently defined if not self.options.all(): for item in defaultoptions: option = MyOption() option.obj = self [setattr(option, k, item[k]) for k in item] option.save() self.save() I get the following error occasionally when I call .save() TypeError: super(type, obj): obj must be an instance or subtype of type How should I edit save() to be solid and error-proof? -
Replacing the value of one form field with another
I have written a piece of code where the user can select an occupation from a select box (teacher, doctor, pilot, etc) and if their occupation isn't in the list they can select 'other' then write their occupation in a textbox underneath. I can successfully detect if they selected 'other' from the dropdown box, but cannot figure out how to populate the 'occupation' field with the data from the 'other' field. if request.method == 'POST': form = OccupationForm(request.POST, request.FILES, instance=request.user.occupation) if form.is_valid(): # if user selected 'other' - get input from text field if form['occupation'].value() == 'other': # this doesnt work #form_data = self.get_form_step_data(form) #form.other = form_data.get('other', '') #form.save() return redirect('#') #form.save() #return redirect('#') else: form = OccupationForm(instance=request.user.occupation) Thank you. -
How to send emails stored in MySQL database in Django
I am building a web application in Django. I am storing all the emails in the MySQL database queue so that the system doesn't slow down while sending those emails. With PHP, I would have configured cronjob to run every minute to query the Database queue and send those emails. With Django, I am not sure, how to do it? Any useful pointers would be really helpful. Thanks -
Django Google social-auth ModuleNotFoundError at /oauth/login/google-oauth2/
I am currently trying to setup social login with social-auth in django for a web app. Whenever I click the button on the webpage that links to a google login, I get this error on the django webpage: ModuleNotFoundError at /oauth/login/google-oauth2/ No module named 'social_core.backends.google.GoogleOAuth2django'; 'social_core.backends.google' is not a package Request Method: GET Request URL: http://127.0.0.1:8000/oauth/login/google-oauth2/ Django Version: 3.0.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'social_core.backends.google.GoogleOAuth2django'; 'social_core.backends.google' is not a package Exception Location: C:\Users\isaac\OneDrive\Desktop\DeliverMeProj\venv\lib\site-packages\social_core\utils.py in import_module, line 56 Python Executable: C:\Users\isaac\OneDrive\Desktop\DeliverMeProj\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\isaac\\OneDrive\\Desktop\\DeliverMeProj', 'C:\\Program Files\\Python38\\python38.zip', 'C:\\Program Files\\Python38\\DLLs', 'C:\\Program Files\\Python38\\lib', 'C:\\Program Files\\Python38', 'C:\\Users\\isaac\\OneDrive\\Desktop\\DeliverMeProj\\venv', 'C:\\Users\\isaac\\OneDrive\\Desktop\\DeliverMeProj\\venv\\lib\\site-packages', 'C:\\Users\\isaac\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Program Files\\Python38\\lib\\site-packages'] Server time: Sun, 26 Apr 2020 04:12:34 +0000 Any idea why this may be happening? -
Comma delimited list to Django template
I'm building website on Django and this is my problem. Btw, I won't post my views.py or models.py or html file because I need to understand the technique. User enters tags separated by commas in a field on my webpage. All I want is to have them like this tags example to be able to format them. It would be great to be able to pass them to Templates as follows: {% for i in tags %} <p class="nice"> {{ i }} </p> {% endfor %} But I've spent 3 days looking for solution, so any approach will do. Thanks. -
Curious to know why I am getting this error in Chrome and Firefox while working on a Django project
So I am getting this error in Chrome and I was curious to know why am I getting this. I am currently learning Django from this link. I have followed exactly everything. Also, even after mapping of the static file its not showing at the top part of the page. I understand one error is due to 'LastPass' extention. But wanted why am I getting the other 3 errors. I would love to know how can I fix them. Also, not sure though but part of the page which I connected with isn't showing up after mapping. Could the above errors be the reason? -
Getting ValueError instead of error message
I have got a function that is supposed to deal with coupons for orders. When the coupon is in database and I will enter in in the form, everything works ok, but when I am trying to add a coupon that, doesn't exist I get an error ValueError at /add-coupon/ Cannot assign "<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/checkout/">": "Order.coupon" must be a "Coupon" instance. , instead of error message for user This coupon does not exist Here's my functions: def get_coupon(request, code): try: coupon = Coupon.objects.get(code=code) return coupon except ObjectDoesNotExist: messages.info(request, "This coupon does not exist") return redirect("core:checkout") class AddCouponView(View): def post(self, *args, **kwargs): form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = Order.objects.get( user=self.request.user, ordered=False) order.coupon = get_coupon(self.request, code) order.save() messages.success(self.request, "Successfully added coupon") return redirect("core:checkout") except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect("core:checkout") Anyone know, where the problem is? -
Is there any way to translate the text coming from the database in django python?
right now I know how to translate text by writing the text between {% trans ..... %} but can I use this form when I retrieve data from mysql database into an array like writing {% tans {{data.2}} %}? when I use compile messages will the locale file contain the retrieved data or it will contain data.2? -
Request Django Template using Ajax
I have a Django template that contains some Django templating blocks. I have another template that contains some JavaScript that does an Ajax request to pull this Django template in. It looks something like this: $.ajax({ url: '/page/', method: 'GET', success: function (data) { console.log($(data).find(".wrapper")); } }); /page.html/ contains the following: {% extends 'core/base.html' %} {% block content %} <div class="example"> ..some..content.. </div> {% endblock %} page.html extends base.html which has a wrapper <div class="wrapper"></div> however, when I run the Ajax code, the console does not find the wrapper class. Is there a way to get the full template page? -
Django Deployment 500 Internal Server Error - Apache2
I have been trying to figure this out for a while but I am not sure of what it's wrong. I have tried modifying the .conf file, uncomment the ServerName but nothing seems to work. Please provide some insight. django_project.conf # ServerName 45.33.82.190 ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/rodrez/PersonalPortfolio/static <Directory /home/rodrez/PersonalPortfolio/static> Require all granted </Directory> Alias /media /home/rodrez/PersonalPortfolio/media <Directory /home/rodrez/PersonalPortfolio/media> Require all granted </Directory> <Directory /home/rodrez/PersonalPortfolio/PersonalPortfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/rodrez/PersonalPortfolio/PersonalPortfolio/wsgi.py WSGIDaemonProcess Portfolio python-path=/home/rodrez/PersonalPortfolio python-home=/home/rodrez/PersonalPortfolio/venv WSGIProcessGroup Portfolio </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet settings.py DEBUG = False ALLOWED_HOSTS = ["45.33.82.190"] ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
Show All Data Using python manage.py shell (Django)
I have tried to migrate my database but am still having issues. I wanted to try and look at all my sites databases via Command Prompt. I want to try and see which columns do or don't exist in models. I did python manage.py shell but then could not work out the queries that would allow me to see all the information in both my sites databases. (project2_env) C:\Users\HP\django_project3>python manage.py shell (InteractiveConsole) >>> from blog.models import Post >>> from django.contrib.auth.models import User >>> User.objects.all() <QuerySet [<User: RossSymonds>, <User: RossTheExplorer>, <User: RossSymondsFacebook>, <User: testuser>]> >>> objects.all() -
Django guardian migration NodeNotFoundError after MIGRATION_MODULES defined for auth
I used django guardian in my project. For a reason, I added a new field to django group model with this code: if not hasattr(Group, 'project'): project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True, related_name='groups') project.contribute_to_class(Group, 'project') So far, everything is ok. But I realized after makemigration command, django adds migration file to outside of my project directory. I want to make this file persistent. I found a solution with defining MIGRATION_MODULES in my settings.py: MIGRATION_MODULES = { 'auth': 'preferences.migrations' # preferences is an app of mine } But this time, django guardian module gives error after makemigration command. The errors are below: Traceback (most recent call last): File "./manage.py", line 16, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django_cassandra_engine/management/commands/makemigrations.py", line 22, in handle super(Command, self).handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 87, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 274, in build_graph raise exc File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 248, in build_graph self.graph.validate_consistency() File "/usr/local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 195, in validate_consistency … -
URL path is added twice when using proxy
Background: I was having a lot of issues with my internet connection so I had to buy an unlimited set of mobile data to be able to work. Unfortunately the internet provider do not allow me to share internet with other devices if the package you bought was an unlimited one. The only way to do it was using a proxy in my Android device to share internet, so with that, I am allowed to use it as hotspot and use internet in my laptop. Issue: I was trying to reach to a server api, and I could from my mobile phone (Android app I am building), but from Postman (in my laptop), I've been getting 404 errors. It is really weird since I can access to absolutely any other webpage/api but not this one specifically. That makes me think it could be something server misconfiguration related, but I am just an Android developer, so I have not idea of what could happen on the backend side. I noticed (as you can see in the image attached: https://imgur.com/a/jtHBA2I) that somehow the URL path is being added twice, the URL should be http://its-jitzone-dev.cloudapp.pe/, but instead, is being modified to http://its-jitzone-dev.cloudapp.pe/http:/its-jitzone-dev.cloudapp.pe. Question: … -
putting a different background image on a different page in a website
Hello so I am using django templating to make a website. So far only the home page has a background image and I want to place a different image on a separate page. Django templating has me use "extends base html". I keep trying to insert a different background page to replace the generic white background page on the search_results.html but the code doesn't work. I want my search_results.html have a different background from home.html. Appreciate the help! Code: I'll only include the ones on the head of each html to ensure not too much code about the body is put Base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title> {% block title %} My Site {% endblock title %} </title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script> <![endif]--> <link href="{% static 'css/bootstrap/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/signinform.css' %}" rel="stylesheet"> <!-- Add your custom CSS to this file --> <link href="{% static 'css/custom.css' %}" rel="stylesheet"> {% block additional_styles %} <style> body {background-image: url(./static/images/golden_gate_bridge.jpg); } </style> {% endblock %} </head> Home.html (this one uses … -
How to write and make correct POST request for nested serializers in DRF?
I have two simple models, and serializers for Course and Department as below: (A course belongs to a department, that is many to one relationship from Course to Department) # models.py # Department Model class Department(models.Model): name = models.CharField(max_length=256) location = models.CharField(max_length=1024) # Course Model class Course(models.Model): code = models.CharField(max_length=15, unique=True) name = models.CharField(max_length=15, unique=True) department = models.ForeignKey(Department, on_delete=models.CASCADE, default=None, null=True, blank=True) ################################### # serializers.py # Department serializer class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = ['id', 'name'] # Course serializer class CourseSerializer(serializers.ModelSerializer): department = DepartmentSerializer() class Meta: model = Course fields = '__all__' After adding some courses through SQL Queries, I made a GET request to the end point localhost:8000/courses/ which gives the expected result. [ { "id": 1, "code": "SS240", "name": "Sociology", "department": { "id": 1, "name": "Humanities" } }, { "id": 2, "code": "CS310", "name": "Data Structures and Algorithms", "department": { "id": 5, "name": "Computer Sciences" } } ] I want to make a POST request to the end point localhost:8000/courses/. Say, I have a department with name = Computer Sciences with id = 5. I want to add a course with code=CS330, name = Object Oriented Design, department = Computer Sciences. How should I write … -
Enter a list of values error in forms when ManyToManyField rendered with different type of input
I changed the widget of my ManyToManyField, tags, in my model to hidden... class PreachingForm(ModelForm): class Meta: model = Preaching fields = ['title', 'text', 'date', 'privacy', 'tags'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}), 'tags': forms.HiddenInput(), #changed to hidden input } ... and in the html, I'm supplying the hidden input with comma separated values <input type="hidden" name="tags" value="Tag1,Tag2" id="id_tags"> The problem is I'm getting a form error saying Enter a list of values and I want to strip(',') the data I got from the hidden input so it might be fixed but I have no idea how to do it. -
Dropdown list with 'other' option which displays a text field
I'm trying to write a Django application with a form which includes a field 'how did you hear about us?' which will give a dropdown list (tv commercial, search engine, etc) including an 'other' option. Upon selecting the 'other' option a box will appear beneath and the user can enter a unique answer. I have attempted this but am stuck. Any help would be greatly appreciated. models.py class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) HEAR_ABOUT_US = ( ('option1', 'Option 1'), ('option2', 'Option 2'), ('other', 'other'), ) hear_about_us = models.CharField('How did you hear about us?', max_length=200, default=None, choices=HEAR_ABOUT_US) views.py def personal_information(request): if request.method == 'POST': form = PersonalInformationForm(request.POST, request.FILES, instance=request.user.personalinformation) if form.is_valid(): if form['hear_about_us'] == 'other': form_data = self.get_form_step_data(form) form.refer = form_data.get('other', '') form.save() return redirect('#') form.save() return redirect('#') else: form = PersonalInformationForm(instance=request.user.personalinformation) context = { 'form' : form } return render(request, 'enrolment/personal_information.html', context) personal_information.html {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Personal Information</legend> {{ form|crispy }} <div id='other' class='other'> <!-- WANT THE TEXT BOX TO APPEAR HERE / I THINK IT WOULD BE BETTER DONE WITHIN THE FORM AND NOT AS A SEPERATE SECTION UNDER IT --> </div> </fieldset> <div class="form-group"> <button class="btn … -
How to set a Foreign Key based on multiple column with django-import-export?
There's a model defining which combination of department/position needs what types of training. Another model shows employees with all related information. All the data comes from xlsx file via django-import-export. The problem is that I can't figure out how to set a foreign key in employees model based on the unique combination of department and position rows, so each employee gets the training field value accordingly. I've tried this solution but it didn't work (or maybe I did something wrong): https://github.com/django-import-export/django-import-export/issues/375 I'm new to programming and this is my first project. Hope some of you can help. Here is my model defining training for each combination of department/position: class TrainingMatrix(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE,blank=False, null=True) position = models.ForeignKey(Position, on_delete=models.CASCADE,blank=False, null=True) training = models.ManyToManyField(Training) Here is the Employee model: class Employee(models.Model): badge = models.CharField(max_length=15, primary_key=True, unique=True) name = models.CharField(max_length=200) department = models.ForeignKey(TrainingMatrix, on_delete=models.CASCADE, null=True, blank=True,related_name='department_name') position = models.ForeignKey(TrainingMatrix, on_delete=models.CASCADE, null=True, blank=True,related_name='position_title') training = models.ForeignKey(TrainingMatrix, on_delete=models.CASCADE, null=True) And the xlsx file's column titles I import: badge, name, position, department -
About modifucation of Whoosh score algorithm
I have 2 questions about whoosh, hope someone can help me. (1) How can I get the number of unique items in given documents, it seem that the funtion “doc_field_length” could only support the number of total tokens in given documents. (2) How can I get the number of a query , for example when a query is " banana apple animal" , the number should be 3. Since I would develop a new scoring method instead of the original one "BM25" My whoosh version 2.7.4, python 3.5.6 Thank you very much -
How to link to other user's profile in django?
What I have been trying is to click the post's author(user that created the post) I want it to redirect me to that user's profile,for example in instagram when you click the user that is on top of the post it redirects you to their profile. Everytime I do that instead of seeing the post's author profile I see the loged in user profile. I think there is something wrong in the views.py file or in the base.html. views.py def profile(request, pk=None): if pk: user = get_object_or_404(User, pk=pk) else: user = request.user args = {'user': user} return render(request, 'profile.html', args) def home(request): created_posts = Create.objects.all().order_by("-added_date") return render(request, 'base.html', {"created_posts": created_posts}) def create(request): if request.method == 'POST': created_date = timezone.now() header1 = request.POST['header'] content1 = request.POST['content'] user = request.user created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user) created_obj.save() print('create created') return redirect('home') else: print('create not created') return render(request, 'create.html') models.py class Create(models.Model): added_date = models.DateTimeField() title = models.CharField(max_length=200) content = models.CharField(max_length=200) user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' urls.py urlpatterns = [ path('', views.home, name='home'), path('profile', views.profile, name='profile'), path('profile/<int:pk>/', views.profile, name='profile_pk'), path('create', views.create, name='create'), ] profile.html (shows user's profile) …