Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migrate / MakeMigrations conundrum
I have a wagtail app that deployed to docker, but then I get a very strange error, below are the steps: Step 1: docker-compose run app /venv/bin/python manage.py makemigrations` Migrations for 'locations': bakerydemo/locations/migrations/0008_alter_locationoperatinghours_day.py - Alter field day on locationoperatinghours` Step 2: docker-compose run app /venv/bin/python manage.py migrate locations Operations to perform: Apply all migrations: locations Running migrations: ===> No migrations to apply. <=== HUH? Your models in app(s): 'locations' have changes that are not yet reflected in a migration, and so won't be applied. ===> Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. <=== DOUBLE HUH? Any wagtail or django or docker afficianados that can tell me what might be going on here? A similar question regarding Heroku mentioned running running the migrations before Heroku-izing, that is something I tried here, but it created an error in my locations app after dockerizing the container. The solution is from https://github.com/wagtail/bakerydemo and I added a few customizations to the locations app. -
How to set-up Memcached for Django?
I am trying to set-up Memcached solution, but it does not seem to work. I tested caching a view only and whole solution with the same result. Here are my settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # CORS 'corsheaders.middleware.CorsMiddleware', # adding caches around CommonMiddleware 'django.middleware.cache.UpdateCacheMiddleware', # NEW 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', # NEW 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } # cache settings CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = '6000' CACHE_MIDDLEWARE_KEY_PREFIX = '' I have installed memcached with Homebrew and is properly running. I have tested it using telnet. I am trying a call that returns a few thousand results, and I see no time gains for the 2nd call and on. Any help on how to figure this out would be greatly appreciated! -
Django production (using gunicorn) - internal server error (no request) until 10-20 requests have been made
I have a production system that has been running for 2+ years now, regularly (daily/weekly) updates. Around 2 months ago, a strange behaviour occurs every time I restart Gunicorn, for the first 10-20 requests made to the web server, I get an internal server error. The errors (when the system is switched to debug=True) all relate the the request being None. The login (allauth) page works a treat, but once I have entered my account details (or any other) - I get internal server error on the following URL. If I reload, it loads AOK. If I browse the site, I get a mixture (semi random) of pages that either load or internal server error. After around 10-20 page load attempts - every thing starts working 100% AOK. No issues. I can then log in as any account, every page works. The above issues on restarting the web server also occurs with any other account login. Its as if there is something that is failing in the middleware or some sort of internal time out before the request details can be stored. But, the database server is fully up and running, no load issues at all. Any thoughts on the … -
Django-Next.js Image Upload Error with Empty Body
Users in my application may alter their profile image, however when I send a request to the backend server, it returns an empty body. Frontend const handleImageChange = useCallback(async (e) => { const confirmation = confirm('Press ok to update profile') if (confirmation) { const form = new FormData() form.append('userProfileImage', e.target.files[0]) const location = process.env.NEXT_PUBLIC_API_URL + `/user/update/profile` const api = await fetch(location, { method: 'Patch', headers: { 'Accept': 'application/json', 'Content-type': 'multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW', }, body: form } ) } }, []) Backend Code class profileImageUpdateView(UpdateAPIView): serializer_class = userProfileImageSerializer http_method_names = ['patch'] def get_object(self): user = self.request.user instance = userProfile.objects.get(user = user) return instance def patch(self, request, *args, **kwargs): print(request.data) return super().patch(request, *args, **kwargs) -
Display filefield object in django templates
models.py enter image description here views.py enter image description here summary_pdf.html enter image description here The problem: enter image description here Can someone help me? I've been stuck in this since morning and haven't found a solution. -
How to avoid recalculation when sorting by a model's property in Django Rest Framework?
I have a simple social media app, with User, Post, and PostVote models. class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) ... @property def score(self): total = 0 for vote in PostVote.objects.all(): if vote.post == self: total += vote.vote return total def get_num_upvotes(self): return PostVote.objects.filter(post=self, vote=1).count() def get_num_downvotes(self): return PostVote.objects.filter(post=self, vote=-1).count() class PostVote(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) post = models.ForeignKey(Post, on_delete=models.SET_NULL, null=True) vote = models.IntegerField() In my views.py, I attempt to calculate the 'top' posts, sorted by score. Here's the view code. class ListCreatePostAPIView(ListCreateAPIView): serializer_class = PostSerializer permission_classes = (IsGoodUser | IsAdminUser,) def get_queryset(self): try: queryset = Post.objects.all().exclude(user=None) queryset = list(queryset) queryset.sort(key=operator.attrgetter("score"), reverse=True) return queryset except: return Post.objects.none() In serializers, I also once again recalculate and return the score, as I'd like to pass it to my front-end. class PostSerializer(serializers.ModelSerializer): score = serializers.SerializerMethodField() num_upvotes = serializers.SerializerMethodField() num_downvotes = serializers.SerializerMethodField() def get_score(self, obj): return obj.get_score() def get_num_upvotes(self, obj): return obj.get_num_upvotes() def get_num_downvotes(self, obj): return obj.get_num_downvotes() class Meta: model = Post fields = ( "score", "num_upvotes", "num_downvotes", ) I know I'm re-calculating the score way too many times, as it's taking 3-4 seconds to return just 50 fake posts / 1250 fake … -
Django migrate primary key from UUID to Slug
I have model AAA with UUID as primary key. Many models have relation to this model. Now I want to migrate them to use Slug as this primary key, to keep slug value in database as a reference. What will be the correct way to do that? from django.db import models from django_extensions.db.fields import AutoSlugField from model_utils.models import UUIDModel # Django models example class AAA(models.Model): id = UUIDField(primary_key=False, version=4, editable=False) title = models.CharField(max_length=255, unique=True) slug = AutoSlugField(populate_from='title', primary_key=False) class BBB(models.Model): aaa = models.ForeignKey(AAA, on_delete=models.CASCADE) # ... other fields here ... -
Model field dependent on same model foreign key object
Title seems complicated but its not really. Lets say I have 2 models: First is Choices that contains a title and boolean to see if the choice is correct or not. class Choice(models.Model): content = models.CharField(max_length=200, default=None) correct = models.BooleanField(default=False) Second is Check that checks if the use has chosen the correct choice: class CheckQuestion(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) selected_choice = models.ForeignKey(Choice, on_delete=models.CASCADE) correct = models.BooleanField(default=None) The correct field must be equal to the correct field of the selected choice. So basically: correct = selected_choice.correct I have tried implementing these using @property like this: @property def correct(self): if self.selected_choice.correct: correct = True else: correct = False return correct And I tried save like this: def save(self,*args,**kwargs): self.correct = self.selected_choice.correct super(CheckQuestion,self).save(*args,**kwargs) But neither worked, property method was giving giving a "cannot be null" error and save method just always returned false. What else can I do? -
Why is Django not able to match URL with trailing slash?
I'm using using the Django rest framework. I'm using Postman with query parameters in the URL. http://localhost:9090/api/payment_management/?cutoffDate=2022-08-05T00:00:00.000Z and my urls.py # this is a child of "/api", using include in the root urls.py urlpatterns += [path('payment_management/', get_cutoff)] I explicitly put a trailing slash at the end of the url. But I get the following from the shell Not Found: /api/payment_management/ [08/Aug/2022 18:33:32] "GET /api/payment_management/?cutoffDate=2022-08-08T00:00:00.000Z HTTP/1.1" 404 I literally put a trailing slash and it's giving me an error. Am I missing something here? APPEND_SLASH is set to true in the settings. -
I need to filter the end points in swagger ui drf. How can i do in Django
I need to customize the swagger ui like filter. Which means if user login the user can see only particular end points. Now I am getting all the end points on my project. Every user can see all end points. How can I achieve that. -
MySQL database breaks while running too many tests in django
I have a Django project with hundreds of tests and after adding about 50 more tests, when I run all of the tests at once using python manage.py test, almost all of the tests raise the following error: Traceback (most recent call last): File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in _execute self.db.validate_no_broken_transaction() File ".../venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 437, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. During handling of the above exception, another exception occurred: File ".../venv/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 653, in first for obj in (self if self.ordered else self.order_by('pk'))[:1]: File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1145, in execute_sql cursor.close() File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 83, in close while self.nextset(): File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 137, in nextset nr = db.next_result() MySQLdb._exceptions.OperationalError: (2006, '') But if I run the tests individually, … -
How do you launch a Tkinter application from a django website
I created a Django website and I want to launch a tkinter program if the user clicks on a button. Can anyone tell me how to do that? Any help is appreciated. -
Getting 504 Gateway Time-out nginx/1.18.0 (Ubuntu) in django nginx
I am facing problems launching my django app in digitalocean. I have done all the needful but I am quite sure I made error some where. Below is my nginx configuration file. What could be the problem . Thanks alot . PLease I would also love to know how to access nginx error log file through command line. server { server_name server_Ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/myproject/smsdigo; } location /media/ { root /home/username/myproject/smsdigo; } location /locale/ { root /home/ebong/myproject/smsdigo; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } server { listen 80; client_max_body_size 3000M; client_body_buffer_size 3000M; client_body_timeout 120; } -
Run task from other Task
I try run task send_request from task start_distribution with apply_async method not work. from celery import shared_task, group from celery.utils.log import get_task_logger from .models import Distribution, Client logger = get_task_logger(__name__) @shared_task(bind=True, max_retries=200, default_retry_delay=30) def send_request(self, distribution_id, client_id): pass @shared_task(bind=True) def start_distribution(self, distribution_id): distribution = Distribution.objects.get(pk=distribution_id) logger.info(f'distribution obj:') logger.info(f' pk: {distribution.pk}') logger.info(f' start date: {distribution.start_date}') logger.info(f' end date: {distribution.end_date}') logger.info(f' tag: {distribution.tag.name}') logger.info(f' mobile_code : {distribution.mobile_code.mobile_code}') logger.info(f' body message : {distribution.body_message}') clients_for_send = Client.objects.filter( mobile_code=distribution.mobile_code, tag=distribution.tag ).all() logger.info('Pk sending client:') [logger.info(client.pk) for client in clients_for_send] g = group(send_request.s(distribution_id, client.pk) for client in clients_for_send) g.apply_async( queue='external_req', expires=distribution.end_date ) -
Django and JS for loop: how to change a variable value into {%static 'path' %}?
I'm trying to find out how to change a path in a picture having JS logic in the Django template. As an example - according to logic in the JS script - change from: hangman_game/img/s0.jpg to hangman_game/img/s1.jpg then to hangman_game/img/s2.jpg ect In the previous framework, it was working. But now, I'm migrating a page to the Django framework. Almost all are ready, but JS for loop syntax mentioned previously isn't working and I'm looking for a way: how to properly set a for loop that will generate a new path to the picture in the HTML file. in my html file I have: <div id="gallows"> <img src="{% static 'hangman_game/img/s0.jpg' %}" alt="" /> </div> This part is ok. The problem is, that this div is linked to for loop in js file where I previously had: var errorCount = 0; if(matched == true) { // errorCount for changing picture: errorCount++; var picture = "img/s" + errorCount + ".jpg" document.getElementById("gallows").innerHTML = '<img src="'+picture+'"alt="" />'; Outside Django, it was working, but after migrating to Django it stopped (obviously). Because JS var picture is a string, I'm pretty sure that I can use {% static %}, but I don't know how. I tried to … -
Testing django migration with sqlite django.db.utils.NotSupportedError
I am upgrading a django project. And I need to run tests. There is a test for the migration of a database scheme, but I receive an error: "django.db.utils.NotSupportedError: SQLite schema editor cannot be used while foreign key constraint checks are enabled. Make sure to disable them before entering a transaction.atomic() context because SQLite does not support disabling them in the middle of a multi-statement transaction." Not only is this error message really long, but I also have no idea left how to fix it. I already tried turning of foreign key checks using PRAGMA foreign_keys = 0;. Is this the right approach? Please help me I am stuck here for days now. executor = db.migrations.executor.MigrationExecutor(db.connection) old_apps = executor.loader.project_state(self.migrate_from).apps executor.migrate(self.migrate) # this line fails This code is run before atomics = {} for db_name in cls._databases_names(): atomic = transaction.atomic(using=db_name) atomic._from_testcase = True atomic.__enter__() atomics[db_name] = atomic return atomics Is there anything I misunderstood? -
Django create user command issue while trying to add a new user through a html form
I have successfully created a table in the database and can add data from the admin panel onto the table but when i used the form displayed on a url by clicking submit a new user is not created. view.py from django.shortcuts import render, redirect from formRegister.models import FormRegister Create your views here. def register(request): if request.method == 'post': first_name = request.POST['fisrt_name'] last_name = request.POST['last_name'] username = request.POST['username'] user = FormRegister.objects.create_user(username=username, first_name=first_name, last_name=last_name) user.save(commit = True); return redirect('/') else: return render (request, 'formRegister.html') -
filter method in try block is not working in django
I have a model called properties which contains product details with the respective user IDs. The user id is called uid in the model. I wrote a function in views.py to get the products that are only posted by logged-in user. I use the filter method in it, but it's not working. How can I solve this? def view_products(request): try: user = request.user.id c = properties.objects.filter(uid=user,status=True) return render(request,'view_products.html',{'c':c}) except: txt = """<script>alert('You have no properties to view...');window.location='/userhome/';</script>""" return HttpResponse(txt)``` -
How can I send a post request in Django Rest Framework where a key has list of json objects?
I am new to Django Rest Framework and django itself. I want to post a request wherein a key has a list of objects. So far, I have created the User_parameter model and I am passing it as a foreign key. I am lost and do not know what to do from here on. Do I need to override create() in the User_Parameters_Serializerserializer or something entirely different? I have added code for my models.py, serializer.py, the function-based view where I am handling the post request and my desired post request outline. Thank you for your time. I really appreciate it. # The post request I want to send looks like this: { "model_path": "some path", "data_path": "some path for csv", "sep": ",", "target_column": "target_column", "label_column": "lable_column", "function_names": "some strings", "user_params": [{ "standard_deviation": between[1-3], "direction": 0 OR 1, "feature_list": "some strings" }] } #models.py class User_Parameters(models.Model): def validate_standard_deviation_number(value): if value not in range(1,4): raise ValidationError( _('%(value)s is not in range: [1-3]'), params={'standard deviation': value}, ) def validate_direction(value): #### 0 - Negative #### 1 - Positive if value not in range(0,2): raise ValidationError( _('%(value)s needs to be either 0 (Negative) or 1 (Positive)'), params={'direction': value}, ) standard_deviation = models.IntegerField(default=1, validators=[validate_standard_deviation_number]) direction = … -
What's an efficient way of synchronizing git pull requests and restarting systemctl services for multiple Django-Q clusters?
I'm running numerous Django-Q clusters (on Ubuntu focal) to perform distributed computing on large data sets. I have production clusters and development clusters that each have their own git branch. I need a way to synchronize the updating and restarting of these cluster systemctl services when changes to their respective git repositories are made. Currently I ssh into each machine and run the following commands. $ git pull $ sudo systemctl restart qcluster I appreciate any ideas you may have. -
adding more then one data in Many to many in Django
I have a project I want to add() more then one data to ManyToMany field class Product(models.Model): name = models.models.CharField(Name) class Tags(models.Model): product_of_names = models.ForeignKey(Product) tag_name = models.models.CharField() class Group(models.Model): tag_group = models.ManyToManyField(Tags) views.py def home(request, pk): product_name = Product.objects.get(pk=pk) tag = Tags.objects.filter(product_of_names=product_name) print(tag.id) >>> 1 >>> 2 >>> 3 insert_data = Group.objects.create() insert_data.tag_group.add(tag) insert_data.save() it add just one I want to add them all in ManyToMany Thanks for any help -
Copy Django Model Input into another Django Database
I am trying to figure out if there was a way that once I uploaded something to one of my Django database files, that, that same upload would also upload to another database file, so if I go to delete one of them, it is saved in the other. class CompanyInfo(models.Model): company_name = models.CharField("Company Name", unique=True, max_length=50, default="") # Identifiers identifier = models.IntegerField(default=0) # Company Information sector = models.CharField("Sector", max_length=50,default="") location = models.CharField("Location", max_length=100, default="") year_founded = models.IntegerField("Year Founded", default=2000) company_description = models.TextField("Company Description", default="") state_registered_in = models.CharField("State of Registration", choices=states_list, max_length=2, default=2) company_url = models.URLField("Company URL", max_length=200, default="", blank=True, null=True) phone_number = models.CharField("Phone Number", max_length=20,default="") company_logo_url = models.ImageField("Company Logo", upload_to=None, height_field=None, width_field=None, max_length=100, blank=True, null=True) facebook = models.URLField("Facebook URL", max_length=200, default="", blank=True, null=True) linkedin = models.URLField("Linkedin URL", max_length=200, default="", blank=True, null=True) instagram = models.URLField("Instagram URL", max_length=200, default="", blank=True, null=True) email = models.EmailField("Email Address", max_length=40,default="") def __str__(self): return "{} from {}".format(self.company_name, self.location) Basically, once these values are created for the "CompanyInfo" class, I want it to also upload itself into another Django class in the exact same way, so if I eventually delete the input in the "CompanyInfo" class, there will still be a saved version in the other created … -
Best practice for Django inline images in TextField?
I have a portfolio site that I am building, and I will be porting a bunch of posts from my GitHub sites, all in Markdown. Thankfully, I have Markdown, and LaText math is working great on the site. However, I can not get images working in the blog body, which is a TextField. I have images working elsewhere on the site. I am looking at django-tinymce and django-inline-media as possible solutions. Any thoughts on these or other alternatives? This is what I have tried in my body so far, with many variations on the path to the image: ### MD  ### HTML <img src= {{ "images/my_image.jpg" }} alt="My image"> With the following turned on in urls.py. from django.contrib.staticfiles.urls import staticfiles_urlpatterns ... urlpatterns += staticfiles_urlpatterns() ### Static <img src="{% static "images/my_image.jpg" %}" alt="My image" /> -
retrieve the value of the variable sent to my detail view (class based view) in get_context data to do a conditional test
I would like to know how to retrieve the value of the variable sent to my detail view in get_context data to do a conditional test and display the result of test and the value send by context_object_name in the models i just have a list of words class Palind(models.Model): mot = models.CharField(max_length=200) def __str__(self): return self.mot the views class PalindDetailView(DetailView): model = Palind context_object_name = "palind" template_name = "pages/palind_detail.html" def get_context_data(self, **kwargs): m = "" # here i need get value of variable send in my detail view context = super(PalindDetailView, self).get_context_data(**kwargs) if m.startswith("k"): test = "ok" else: test = "not ok" context['test'] = test return context in my urls.py path("<int:pk>/", PalindDetailView.as_view(),name="palind_detail") in template <p> {{ palind.mot }} {{ test }} </p> thank you for all info -
How to go building customer user Token authentication in DRF?
I am trying to do user Token authentication using DRF and I have done that succesfully, but for default USER Model of django , I am want to properly configure the fields in that like I dont want username and wanna make email & password for login and wanna add more fields like first_name and last_name during signup process. I want to add one more field which will say whether this is a student or teacher or a superuser. during signup the data will get stored accordingly. I am messed up with this form past 3 days, and currently exhausted, kindly help me in mitigating this issue.