Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MySQL Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535
I am currently migrating my tables to a new MySQL database from SQLite. There were no issues when I migrate to SQLite but when I try to migrate on to MySQL, I get the error above. I think it was due to my textfields taking up much of the space so I added a max_length=500 attribute to all of them but the error persists. This is the error: Is there a way to resize the textfield, or resize the maximum row size? Thanks in advance. -
Django URL Not Matching with Intended View
I'm having trouble figuring out why tag pages for my blog are trying to pass to a different view than the one I intend. My /tag/ url's should go to TagsListView, but instead are going to PostDetail. My url structure: app_name = 'blog' urlpatterns = [ path('', views.home, name='home'), path('search/', SearchResultsView.as_view(), name='search_results'), path('tag/<slug:slug>', views.TagsListView.as_view(), name='blog_tag'), path('<slug:slug>/', views.CategoriesDetail.as_view(), name='categories_detail'), path('<slug:categories_detail>/<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('<slug:categories_detail>/<slug:slug>/comment', views.CommentCreateView.as_view(), name='post_comment_create'), ] View: class TagsListView(ListView): model = Tag template_name = 'blog/tags.html' Template (implementation has to be dynamic): <a href="/{{ tag.slug }}"><h4><span class="badge badge-primary">{{ tag }}</span></h4></a> For some reason the url, domain.com/tag/tagname will try to match and run through the PostDetail view and 404, instead of the TagListView. Everything seems like it should match, so I'm not sure why it's skipping that over. Also, I believe I should have the model for the TagListView set to Post (blog posts), and create a custom queryset that filters based on the slug for the requested tag. Correct? Or is it the other way around? I haven't gotten to that point to test yet and wondering the best approach there. Thanks. -
Axios is sending OPTIONS instead of POST to Django
I'm using Django Rest Framework with a front-end in Vue. I'm using axios to make POST requests to Django, but the Django server is receiving OPTIONS requests, as you can see in the server log. "OPTIONS /save/ HTTP/1.1" 200 0 Broken pipe from ('127.0.0.1', 59396) The problem doesn't appear to be in the server, since CORS is configured correctly and I can send a POST request with Postman. Here's the javascript code async save() { let data = { "name": this.name, "title": this.title, } let config = { header : { "Content-Type": "application/json", } } response = await axios.post( 'http://127.0.0.1:8000/save/', data, config ) } -
Django: ModuleNotFoundError: No module named (django unable to import modules?)
When attempting to debug a file named "formulas.py", I got the following error: ModuleNotFoundError: No module named 'ingredients'. This was strange, as yesterday I debugged the file and it worked perfectly. To my knowledge, I didn't change anything that should have impeded django's ability to load my module. My file structure is the following: Blocky_alchemists blocky_alchemists ingredients media playground database manage.py In playground there are (among others) my formulas.py and views.py, and in ingredients I have my models.py which contains the model called "Ingredient". I am trying to use this model to create a queryset, so I used the following line of code in formulas.py: from ingredients.models import Ingredient When running the file formulas.py however, it runs until the above line of code, and then returns: Traceback (most recent call last): esktop\blocky_alchemists'; & 'C:\Users\ticov.virtualenvs\blocky_alchemists-KNju3Ys9\Scripts\python.exe' 'c:\Users\ticov.vscode\extension File "c:\Users\ticov\desktop\blocky_alchemists\playground\formulas.puncher' '54184' '--' 'c:\Users\ticov\desktop\blocky_alchemists\playground\formulas.py' y", line 3, in from ingredients.models import Ingredient y", line 3, in ModuleNotFoundError: No module named 'ingredients' In my main settings.py I have added 'ingredients' to the installed apps, but it is still unable to find it. Does anyone know how to fix this? Thanks in advance! -
post_save fails to create instance for OneToOneField
In attempting to use signals for the first time, I'm testing the scenario where once a User instance is created a Profile is created and is attached to the User. However, the test is not passing. I've read similar questions, but two signals are used. Django create profile for user signal Create a post_save signal that creates a profile object for me Why are two signals being used in those cases? How can I get a profile created in my case? from django.test import TestCase from ..forms import CreateProfileForm class TestNewUserProfileCreated(TestCase): '''Verify that a user profile is created once a user has registered with a username and password.''' @classmethod def setUpTestData(cls): user_submitted_data = { "username": "MockUser", "password1": "#hf7*3k", "password2": "#hf7*3k" } cls.form = CreateProfileForm(**user_submitted_data) cls.user = cls.form.save() def test_new_user_profile_form_pass(self): self.assertTrue(hasattr(self.user, 'profile')) forms.py class CreateProfileForm(UserCreationForm): def __init__(self, *args, **kwargs): pass def save(self, *args, **kwargs): pass class Meta: pass models.py class Profile(Model): user = OneToOneField( settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="profile" ) favorite_images = ManyToManyField( FavoriteImage, related_name="favorites" ) follows = ManyToManyField("self", related_name="followers") following = ManyToManyField("self", related_name="following") receivers.py from .models import Profile def create_profile_receiver(sender, instance, created, **kwargs): if created: profile = Profile.objects.create(user=instance) instance.profile = profile app.py from django.apps import AppConfig from django.conf import settings from django.db.models.signals … -
Listen for notification on React Native app from Django server
I'm currently developing a programme that will need app developers to listen out for a (ideally) silent notification from my Django server. Right now, I'm testing with a React Native app I've made but I don't know how to implement something like this. Basically, when something happens in relation to a certain app on the server end of things, I want to send a notification to that client app to react accordingly. Almost like a webhook but for mobile. It's important to know that in practice, I won't be the owner and developer of both the client-side app and the server-side software, just the server-side. If anyone knows how to do it natively on either Android or iOS that would be appreciated too. -
Django: How to add next to manual login redirect?
I have a view: def create_something(request): ... I want to redirect to login if a person isn't logged in. Normally I'd use: @login_required def create_something(request): ... but 🍑.... I want to add a message before the redirect. I wanted to do it like this: def create_something(request): if not request.user.is_authenticated: messages.info(request, 'You must be logged in to create a thing 👀.') return redirect('login') ... However, that doesn't include a ?next in the url to go back to the page I was going to. So my question is: How would you manually redirect back to the login page WITH a manually added ?next query? -
Spanning multi-valued relationships
I read the django documentation and I found something confusing! https://docs.djangoproject.com/en/3.2/topics/db/queries/#spanning-multi-valued-relationships. It is stated that "When you are filtering an object based on a ManyToManyField or a reverse ForeignKey, there are two different sorts of filter you may be interested in" "To select all blogs that contain entries with both “Lennon” in the headline and that were published in 2008 (the same entry satisfying both conditions), we would write:" Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008) "To select all blogs that contain an entry with “Lennon” in the headline as well as an entry that was published in 2008, we would write:" Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) "Suppose there is only one blog that had both entries containing “Lennon” and entries from 2008, but that none of the entries from 2008 contained “Lennon”. The first query would not return any blogs, but the second query would return that one blog" So, by reading this guide, multiple questions have been created in my mind: 1- What is difference between these two types of filtering? what I know is that both of them must return blogs that contain both 'Lennon' in headline and was published in 2008. I can't find out the point. 2- The Document says this rule is just … -
why i am getting TypeError: create_superuser() missing 1 required positional argument: 'username' in AbstractUser?
I am have written a custom User model and when trying to create superuser got the following error**:-** TypeError: create_superuser() missing 1 required positional argument: 'username' when i run the command for creating superuser, django did't asked me to enter username field. Model Class:- class CustomUser(AbstractUser): email = models.EmailField(max_length=250, null=False, unique=True) name = models.CharField(max_length=50, null=False) username = models.CharField(max_length=50, null=False) password = models.CharField(max_length=15, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] this is all what i have written, and i am new django unable to figure out what i am doing wrong. Thanks in advance. Hope to here from you soon. -
Django: how apply uuid django.contrib.auth migration
I create a project Django with Postgres. I only apply to User model. But I want to use uuid for field primary key id in all models in app django.contrib.auth such as User, Permission, Group ... Beside, I want to apply uuid for all migrations of my project How can I do that, please help me. -
Django API path restrict
I am pretty new to Django REST framework and have made an app with React/Django REST by following a tutorial. I am including an example on how it's done urls.py urlpatterns = [ path('', TemplateView.as_view(template_name='index.html')), path('api/register/', RegisterAPI.as_view(), name='register'), ] views.py class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): ... and then let's say index.html contains registration form that generates JSON request and sends it to the register url included above and then it obviously gets processed by the view and response is generated. This is all cool and simple. However, now let's say that some user goes to the url http://127.0.0.1:8000/api/register/. He/she will then access my auto built django rest page with the form that doesn't look very "production-ready". I was wondering if there was a way to allow this page to be accessed by the react, but when we try accessing this url physically, I want the page to redirect us to some other page, or show 404 error. Is there a way to do this? Thanks for the help! -
Django form not rendering widget
I can't figure out, why the django form widget is not rendered in the browser. This is my form: from django import forms from .models import RealEstateTax class CreateRealEstateForm(forms.ModelForm): class Meta: model = RealEstateTax fields = ['invoice_number',] widget = { 'invoice_number': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Text goes here'}), } Just for testing purposes, I reattributed the field as a Textarea and gave it a class where the text should appear red. This is the template: {% extends 'main.html' %} {% load static %} {% block title %} Create Realestate Tax {% endblock %} {% block content %} <style> .form-control { color: red; } </style> <form method="post"> <div class="form-group"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-info">Send</button> </div> </form> {% endblock %} When I inspect the element in the browser, there is no class, it is not a Textarea and the text is not red: This is what I specified in the view: from realestate.models import RealEstate from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from django.db.models import Sum from realestate.models import RealEstate from .forms import CreateRealEstateForm def create_real_tax(request): form = CreateRealEstateForm if request.method == 'POST': form = CreateRealEstateForm(request.POST) if form.is_valid(): form.save() print(form.base_fields) context = … -
Django: Query database from Channels consumers
I had a Django app which had live chat working. Now I am trying to add a query to the database within the connect method. I am following the Channels documentation, and tried the solution in this other StackOverflow question but nothing is working. Below is my code. The error I'm seeing in the Javascript console is WebSocket connection to 'ws://localhost:9008/ws/chat/334/' failed: WebSocket is closed before the connection is established. I do have redis-server running on localhost and that was working before, so that's not a problem. async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name valid_connection = await database_sync_to_async(self.verify_chat_room_key)() # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def verify_chat_room_key(self): trans = database_sync_to_async(Transaction.objects.get)(id=self.room_name) return True -
Django view filter count
I want to get to know the number 'tasks' (Pendentes) for each 'Customer' (Cliente) I have this models in my models.py: class Cliente(models.Model): id = models.IntegerField(primary_key=True) nome = models.CharField(max_length=200, help_text="Nome") localidade = models.CharField(max_length=100, help_text="Localidade") [...] class Pendente(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID Unico") cliente = models.ForeignKey('Cliente', on_delete=models.RESTRICT, blank=True, null=True) memo = models.TextField(null=True, blank=True, help_text="Memória Descritiva", max_length=200) criado = models.DateField(default=date.today, null=True, blank=True, help_text="Data registo ") concluir = models.DateField(null=True, blank=True, help_text="Data de execução máxima ") tecnico = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) tecnicoatribuido = models.ForeignKey('TecnicoAtribuido', on_delete=models.SET_NULL, blank=True, null=True) Basicly i want to run this sql: "select A.id, A.nome, A.localidade, count(B.id) as tarefas from todolist_pendente B LEFT JOIN todolist_cliente A ON A.id = B.cliente_id GROUP by A.id;" Can't seem to figure out how it would work on a view. I'm able to get the count per cliente with : resultado = Pendente.objects.values('cliente').order_by('cliente').annotate(count=Count('id')) But this doesn't render the name of each customer on the template. On my template I'm using : <ul> {% for obj in resultado %} <li>{{ obj.cliente}} : {{ obj.count}}</li> {% endfor %} </ul> This is rendering: 6 : 2 35 : 1 40 : 1 92 : 1 106 : 1 105 : 1 is there a way to get the … -
django-compressor "Settings has no attribute"
I included django-compressor in version 2.4.1 to my django-project to compile scss-files. I followed the quickstart guide at https://django-compressor.readthedocs.io/en/stable/quickstart/ When I am now open the page where I included the css-file I got an error with regarding to this line {% compress css %} The error: 'Settings' object has no attribute 'COMPRESS_DEBUG_TOGGLE' When I add the value manually it comes to the next attribute which is not set and so on for all attributes. Regarding to the documentation the attributes should have a standard value. Why is my project not recognizing that there are default values set to the variables? -
How can I combine the data of two querysets?
I have a Model Poller and a Model Vote which stores the votes made by a user for a specific poller. Additionally I use this Model of a third party package to handle comments made to a Poller. Now I would like to attach the information which vote the creator of a comment selected to each comment (comments can only be done if the user already voted). So in my view I got this: def single_poller(request, poller_id): """ renders a specific poller with prepopulated meta according to previous user interaction, e.g. votes and likes """ # Retrieve the item via get poller = Poller.objects.get(poller_id=poller_id) # Get votes and users for rendering comments with vote 1 or vote 2 votes = Vote.objects.filter( poller=poller, user__in=poller.poller_comments.all().values('user') ) Votes Model class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) How can I now link the votes queryset's information to the comments queryset so I can determine for each comment whether the commentor voted for poller_choice_one_vote or poller_choice_two_vote? Cause I think the votes queryset isn't aware of the comment's queryset yet somehow when rendering the template since the comments queryset is rendered by the … -
Filter Data between two number Django
How can I filter my model obj in range of numbers some thing like Item.objects.filter(4500< price < 7500) I try for loop but its too slow and take lots of sources -
How to stop adding delete button to first form in djagno formset?
I am creating a dynamic form using formsets. So basically when user click on "Add Field" button a new form will be created and when user click on trash icon the form should be removed ! Now the problem is that, delete icon is displaying on first default form also so if the click on the icon the default form also gets removed ! How to add delete icon on the cloned forms ? <script> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function addForm(btn, prefix) { var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); var row = $('.dynamic-form:first').clone(true).get(0); $(row).removeAttr('id').insertAfter($('.dynamic-form:last')).children('.hidden').removeClass('hidden'); $(row).children().not(':last').children().each(function() { updateElementIndex(this, prefix, formCount); $(this).val(''); }); $(row).find('.delete-row').click(function() { deleteForm(this, prefix); }); $('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1); return false; } function deleteForm(btn, prefix) { $(btn).parents('.dynamic-form').remove(); var forms = $('.dynamic-form'); $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length); for (var i=0, formCount=forms.length; i<formCount; i++) { $(forms.get(i)).children().not(':last').children().each(function() { updateElementIndex(this, prefix, i); }); } return false; } </script> <script> $(function () { $('.add-row').click(function() { return addForm(this, 'form'); }); $('.delete-row').click(function() { return deleteForm(this, … -
Django can't connect mysql 8.0.how can fix?
Because I upgraded MySQL 5.7 to MySQL 8.0.26, the dajango project cannot connect to MySQL; python version:3.6 django version:3.2.7 mysqlclient version:1.4.6 pymysql version:0.9.3 mysql-connector-python version:8.0.19 django setting.py database: enter image description here error: enter image description here -
using django regroup tag equivalent in python
I have a project built with django whereby I use django's template engine. I want to switch the frontend from django template engine to reactjs. Everything works quite well using django template engine. I have googled and stackoverflowed everywhere but no solution to my problem. Here is what I did using django template engine (everything works well): # models.py class Post(models.Model): ... publish = models.DateTimeField( default=timezone.now, verbose_name=("Publication date"), ) ... My templatetag looks like this: # blog_tags.py @register.inclusion_tag('blog/month_links_snippet.html') def render_month_links(): all_posts = Post.published.dates('publish', 'month', order='DESC') return {'all_posts': all_posts,} My template file looks like this: # blog/month_links_snippet.html {% regroup all_posts by year as dates_by_year %} <div class="sidebar"> <ul class="active list-unstyled"> {% for month in dates_by_year %} <li id="year{{ month.grouper }}"{% if forloop.first %} class="active"{% endif %}> <h2 style="font-size: 18px"><a href="{% url 'blog:archive-year' month.grouper %}">{{ month.grouper }}</a> <i class="collapsing-icon fa fa-plus"></i></h2> <div class="collapsing-content"> <ul class="list-unstyled"> {% for d in month.list %} <li><a href="{% url 'blog:archive_month_numeric' d|date:"Y" d|date:"n" %}">{{ d|date:"F Y" }}</a></li> {% endfor %} </ul> </div> </li> {% endfor %} </ul> </div> Everything works as expected. Take a look: Blog post archive How can I achieve this using django rest framework? Please remember that this data will later be consumed by reactjs. … -
Nginx giving out a 413 Request entity too large
I have a Django app serving React static files powered by Nginx running in Docker containers. As I'm trying to upload some larger files via my web app I keep receiving 413 Request entity too large from Nginx directly Here is my Nginx config / # nginx -T nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful # configuration file /etc/nginx/nginx.conf: user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } # configuration file /etc/nginx/mime.types: types { text/html html htm shtml; text/css css; text/xml xml; image/gif gif; image/jpeg jpeg jpg; application/javascript js; application/atom+xml atom; application/rss+xml rss; text/mathml mml; text/plain txt; text/vnd.sun.j2me.app-descriptor jad; text/vnd.wap.wml wml; text/x-component htc; image/png png; image/svg+xml svg svgz; image/tiff tif tiff; image/vnd.wap.wbmp wbmp; image/webp webp; image/x-icon ico; image/x-jng jng; image/x-ms-bmp bmp; font/woff woff; font/woff2 woff2; application/java-archive jar war ear; application/json json; application/mac-binhex40 hqx; application/msword doc; application/pdf pdf; application/postscript ps eps ai; application/rtf rtf; application/vnd.apple.mpegurl m3u8; application/vnd.google-earth.kml+xml kml; application/vnd.google-earth.kmz kmz; application/vnd.ms-excel xls; application/vnd.ms-fontobject eot; … -
Django querying data out of models and get sum of field
I'm just beginning with Django and have the following question: I have set up a model looking like class Automation_Apps(models.Model): app_name = models.CharField(max_length=50) app_description = models.TextField(blank=True) view_function_name = models.CharField(max_length=50) time_saver_min = models.IntegerField() implementation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.app_name class Automation_Usage(models.Model): used_app = models.ForeignKey(Automation_Apps, on_delete=models.CASCADE) used_by_user = models.ForeignKey(User, on_delete=models.CASCADE) used_on_date = models.DateTimeField(auto_now_add=True) I would like to query it like: Select Sum(time_saver_min) from Automation_Apps, Automation_Usage where Automation_Usage.used_app = Automation_Apps.app_name I would like to do this in my view. Any help is much appreciated. -
How can I solve the ImproperlyConfigured error in Django
I just started learning django and I'm getting the following error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. when running the command from myApp.models import Dragons. This is ``models.py`: from django.db import models # Create your models here. class Dragons(models.Model): rider = models.CharField(max_length=200) dragon = models.CharField(max_length=60) This is INSTALLED_APPS inside settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myApp.apps.MyappConfig', ] This is àpps.py: from django.apps import AppConfig class MyappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myApp.apps' And this is the folder structure: Solutions that didn't work: Restarting the server. -
Can we print name in the image using django?
(https://footballshirtmaker.com/) this website prints desired name in the jersey and I want that feature in my e-commerce project and I don't have any idea? -
Problem detecting a language outside views.py in Django
I have a Django app that loads a list of countries and states from a json file and translate them using a custom translaction dictonary little tool I created for this purpose. I don't use gettext for this specific task because gettext doesn't work with data coming from databases or files. First the file that handles the json file from django.utils.translation import gettext_lazy as _, get_language import importlib current_lng = get_language() # importing the appropriate translation file based on current_lng imp = importlib.import_module("countries.translations.countries_%s" % current_lng) import json def readJson(filename): with open(filename, 'r', encoding="utf8") as fp: return json.load(fp) def get_country(): filepath = 'myproj/static/data/countries_states_cities.json' all_data = readJson(filepath) all_countries = [('----', _("--- Select a Country ---"))] for x in all_data: y = (x['name'], imp.t_countries(x['name'])) all_countries.append(y) return all_countries # the files continues with other function but they are not relevant arr_country = get_country() I use countries_hangler.py in forms.py from django import forms from .models import Address from django.conf import settings from .countries_handler import arr_country from django.utils.translation import gettext_lazy as _ class AddressForm(forms.ModelForm): # data = [] #def __init__(self, data): # self.data = data country = forms.ChoiceField( choices = arr_country, required = False, label=_('Company Country Location'), widget=forms.Select(attrs={'class':'form-control', 'id': 'id_country'}), ) def get_state_by_country(self, country): return return_state_by_country(country) …