Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - "You may also like" queries
I'm writing on a Forum Software for a while now and I was asking myself as this is also my first Django app how to accomplish a fancy solution to display similar posts items the user maybe also like to see. At least I don't understand how to put all this together on the one side I need the actual post the user is currently viewing, second I might need a somekind of history for previously viewed posts by the user and third I might need tags I can to query for. Does somebody maybe has a good example for me? Thanks in advance -
Django: 'NoneType' object has no attribute 'strftime' error on assigning DateField to a variable in a model class method
I have a Blog model method that create a unique serial number based on the blog's submission_date, submission_time, and id of the blog instance. The Blog model: class Blog(models.Model): title = models.CharField(max_length = 50, blank=False) body = models.TextField() slug = models.SlugField(max_length=50, blank=True) serial_no = models.CharField(max_length=15, blank=True) submit_date = models.DateField(auto_now=True, auto_now_add=False) submit_time = models.TimeField(auto_now=True, auto_now_add=False) ... In the method, I'm taking the date and time fields and converting them to strings through strftime(), then concatenating them. This is the method: def get_serial_no(self): s_date = self.submit_date s_time = self.submit_time str_date = s_date.strftime('%Y%m%d') str_time = s_time.strftime('%H%m') serial = self.id + str_date + str_time return serial I am overriding the save() method to populate slug and serial_no field. The error is only occurring when I'm saving an article. It's pointing to this line: str_date = s_date.strftime('%Y%m%d'); with the error: 'NoneType' object has no attribute 'strftime'. As far as I understand I am properly referencing to the Date type. Therefore, it should call its strftime() function. What am I doing wrong? -
How can I solve this problem of connecting MySQL with Django
enter image description here This is the issue from running the server -
value too long for type character Django Factory
I have below OrderDataFactory class. class OrderDataFactory(factory.django.DjangoModelFactory): class Meta: model = models.OrderData order = factory.SubFactory(OrderFactory) category = 'single', quantity = 75.6 price_per_kg = 10.5 sku = factory.SelfAttribute('crop_data.id') class Params: crop_data = factory.SubFactory(CropFactory) models.py class OrderData(models.Model): CATEGORY_CHOICES = ( (SKUCategory.SINGLE, 'Single Sku'), (SKUCategory.COMBO, 'Combo Sku'), ) sku = models.PositiveIntegerField(null=False, validators=[MinValueValidator(1)]) order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.FloatField() price_per_kg = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=8) class Meta: unique_together = (('sku', 'order', 'category'),) Category.py class SKUCategory: SINGLE = 'single' COMBO = 'combo' i am getting following error. django.db.utils.DataError: value too long for type character varying(8) even max length for category is 6. -
Explain about the function at end of the code. It is in Django choices field. Explain what that function do in Django
Explain about the function at end of the code. It is in Django choices field. Explain what that function do in Django. from django.db import model class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMEN def is_upperclass(self): return self.year_in_school in (self.JUNIOR, self.SENIOR) -
Django admin not responding on host site
I am working on Django admin creation using "python manage.py createsuperuser" in the shell.I created username,email and password and then ran the server using "python manage.py runserver" in the terminal of PyCharm. What I got is: (venv) H:\django project\mysite1>python manage.py createsuperuser Username (leave blank to use 'maitreya'): mtr007 Email address: maitreya@gmail.com Password: Password (again): Superuser created successfully. AND AFTER THIS I RAN THE SERVER (venv) H:\django project\mysite1>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 26, 2020 - 11:32:06 Django version 3.0.5, using settings 'mysite1.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [26/Apr/2020 11:32:08] "GET / HTTP/1.1" 404 2028 [26/Apr/2020 11:32:13] "GET /admin/ HTTP/1.1" 302 0 [26/Apr/2020 11:32:13] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [26/Apr/2020 11:32:27] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 Now What happens is that the web page has created a Django administration login and accepting my username and password but suddenly the site stops working. I am posting a screenshot of the site. Can someone address and solve what should I do(should install some module or verify the path etc.) or look for new versions of some django documentations. -
ValueError: source code string cannot contain null bytes in Django
Right now, I am learning django framework and I got stuck on the following problem Here is the error message Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x044BF148> Traceback (most recent call last): File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\management\base.py", line 376, in check all_issues = self._run_checks( File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\web_projects\pages\pages_project\urls.py", line 21, in <module> path('', include('pages.urls')), File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\urls\conf.py", line … -
Delete operation using Serializes
In official document serializers class show only create & update method only. There is any way to perform delete method? is say Yes how? if say No why? -
Bad request(400) for POST request on django rest-framework api via jquery [duplicate]
I am quite new to django and jquery. I am trying to perform a post request on: my model class part_list(models.Model): designID = models.ForeignKey('modules', on_delete=models.CASCADE) PartID = models.ForeignKey('parts',on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return "DesignID :{}, PartID :{}".format(self.designID,self.PartID) class Meta: unique_together = (('designID','PartID')) my serializer class sub_part_list_serializer(serializers.ModelSerializer): class Meta: model = part_list fields = ('designID', 'PartID', 'quantity') my view class sub_part(generics.ListCreateAPIView): serializer_class = sub_part_list_serializer def get_queryset(self): queryset = part_list.objects.all() designID = self.request.query_params.get('designID',None) print(self.request) if designID is not None: queryset = queryset.filter(designID__exact=designID) return queryset and my jquery $('#test').on('click', function(){ var data1 = {}; data1["designID"] = "bar-123"; data1["PartID"] = "A102"; data1["quantity"] = 3; console.log(data1); $.ajax({ type: "POST", url: "bon/sub_part/", data: data1, contentType: "application/json; charset=utf-8", success: function(data){ alert(data); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("some error " + String(errorThrown) + String(textStatus) + String(XMLHttpRequest.responseText)); } }); the error it is showing is Bad Requesterror{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} when I am making post requests directly from the API it is working fine. I am not using any user authentication. I also tried to add the csrf token in the request header but nothing changed Please Help! -
Is there anyway to pass more than 2 arguments in Django's template url function?
I want to pass 3 arguments to this path: path('assignment/<str:class_id>/<str:assignment_id>/<str:edit>', views.assignment, name='teacher-assignment') Here is the template code: <a href="{% url 'teacher-assignment' class_id=class_id assignment_id=assignment.id|uuid_to_str edit='edit=false' %}">{{ assignment.assignment_name }}</a> However, Django throws a no reverse match found error showing only 2 of these arguments listed in the passed arguments. The template url function's comments also show only 2 arguments being passed. How would I pass 3 arguments to the URL dispatcher? -
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/')