Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm struggling to resolve 2 seemingly ireconsilable dependancy clashes
I have 2 libraries which a code base I'm trying to load and run locally use: django-storages==1.10.1 django-pyodbc-azure==2.1.0.0 The problem I have is I either get this error: django-storages 1.13.2 requires Django>=3.2, but you have django 2.2 which is incompatible., or this one if I try to resolve the first error: django-pyodbc-azure 2.1.0.0 requires Django<2.2,>=2.1.0, but you have django 2.2.1 which is incompatible. Resolving one causes a upgrade or downgrade of Django which triggers either one or the other of the above errors. How do I resolve this? Thanks! -
How to count posts that each hashtag has in django queryset
class Post(models.Model): post_uuid=models.UUIDField( default=uuid.uuid4, editable=False) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_language = models.BooleanField(default=True) description = models.CharField(max_length=400, null=True, blank=True) hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return '{}'.format(self.post.id) class HashtagName(models.Model): Hashtagname = models.UUIDField(default=uuid.uuid4, editable=False) hashtag_name = models.CharField(max_length=150, null=False, unique=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return self.hashtag_name class Hashtag(models.Model): hashtag_uuid = models.UUIDField(default=uuid.uuid4, editable=False) tag_name = models.ForeignKey(HashtagName,on_delete=models.CASCADE) posts = models.ForeignKey(Post, on_delete=models.CASCADE) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return self.hashtag_uuid I have these classes. Im making one api to get the list of trending hashtag What im trying to do is when someone type #planet And i have list of these below hashtag #planetearth Used in 7 posts #planetjuypiter used in 5 posts #planetmercury used in 3 posts Etc That starts with the keyword i have passed from frontend. So i want to get the list of top 10 hashtag that starts with the keyword I passed from front end and based on in how many posts they are used. -
Django not parsing Unity WWWForm multipart/form-data
I have a django backend (3.2.15) with django rest framework (3.13.1) and I have an endpoint where I post a string and a file. When I use postman, it works fine, but using Unity WWWForm library, it doesn't. The problem that I see, is that when I receive the post from Unity, for some reason, is not parse correctly, for instance, if I send only the string value, the request.POST value is set as <QueryDict: {'personal_account': ['13123123123\r\n--e2FxgWvU1dzZvTibOpwyxx07RvZnbNzj2BhnBpUY--\r\n']}> instead of <QueryDict: {'personal_account': ['13123123123']}> as it works with postman. When I include the file in the form, request.POST and request.FILE are simply empty. Here is my code: Unity: List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); formData.Add(new MultipartFormFileSection("file", file, AccountsManager.Instance.uiTransferNotificationsBuy.fileName, "image/jpeg")); formData.Add(new MultipartFormDataSection("string", string)); UnityWebRequest www = UnityWebRequest.Post(url, formData); byte[] boundary = UnityWebRequest.GenerateBoundary(); www.SetRequestHeader("Content-Type", "multipart/form-data; boundary = " + System.Text.Encoding.UTF8.GetString(boundary)); www.SetRequestHeader("x-api-key", apiKey); www.SetRequestHeader("Authorization", PlayerPrefs.GetString("IdToken")); www.downloadHandler = new DownloadHandlerBuffer(); yield return www.SendWebRequest(); Django is a default create method from ModelViewSet Couldn't find any reported issues in both projects. Any idea what might be the issue? Thanks -
I need to make this time task for my advertisement website
I have created_at in django table. How can I gather a week with recent datetime. I need to do it + 7 days. Just tell me how can I do it. I need to get 7 days -
GSMA mobile money api integration for mobile payment
I want to integrate GSMA mobile money with my python code. Didn't find any github repo for the same, also there is no SDK for python on GSMA developer portal. Can anyone help ? -
Permisos para editar unicamente un campo en un Modelo. Django
estoy desarrollando una app la cual va a tener distintos tipos de usuarios, y el objetivo es que en un Modelo puntual, se complete de manera comunitaria. Ej: Tengo una app que tiene creados 3 tipos de usuarios: UsuarioTotal, UsuarioParcial, UsuarioMinimo. Una clase que es ModeloFamilia, que consta de 10 campos (int, char, date, etc) Puedo hacer que UsuarioParcial vea todo el modelo, pero unicamente pueda editar los 4 primeros campos del mismo? UsuarioTotal pueda ver/editar todo. Y UsuarioMinimo, solo pueda editar 1 campo que coincide con uno de los de UsuarioParcial? Como podria resolverlo? de momento no tengo vistas, estoy manejando todo desde el panel de Admin de Django. Muchas gracias por su tiempo! Probé cambiar los permisos desde admin pero es a nivel Objeto, no campo de objeto. -
I want to use product foreign key but it is too slow
class Item(models.Model): title = models.CharField(max_length=100) model = models.CharField(max_length=100, blank=True, null=True) sku = models.CharField(max_length=100, blank=True, null=True) ean = models.CharField(max_length=100, blank=True, null=True) price = models.FloatField(blank=True, null=True) inventory = models.IntegerField(blank=True, null=True) sales_price = models.DecimalField(decimal_places=2, max_digits=15, blank=True, null=True) web_shop_price = models.DecimalField(decimal_places=2, max_digits=15, blank=True, null=True) bb_price = models.DecimalField(decimal_places=2, max_digits=15, blank=True, null=True) discount_price = models.FloatField(blank=True, null=True) categorie = models.ForeignKey(Categorie, on_delete=models.CASCADE, null=True, blank=True) # slug = models.SlugField(blank=True, null=True) description = models.TextField(blank=True, null=True) image = models.ImageField(upload_to='images', null=True, blank=True) As you can see, This is not a small amount of queries. class SaleItem(models.Model): invoice_id = models.PositiveIntegerField(auto_created=True) product = models.ForeignKey(Item, on_delete=models.CASCADE) I have about 15000+ Item models registered in database. therefore when i use the foreign key in SaleItem model, it takes too much time, drops performance. I am using Jawsdb(a 10$ plan) and Mysql. I think other than the huge data, its because the ram of the database is shared. This is taking my life. I need help seriously. -
Updating records in Django based on date
I have a model in Django called Marketplaces, which has attributes Name, Status and date. The default value for Status is "Open". I want it so that the Status of a Marketplace object is updated from "Open" to "Completed" after the date has passed. models.py: class EventStatus(models.TextChoices): Open = "Open" Closed = "Closed" Completed = "Completed" Archived = "Archived" class Marketplace(models.Model): Creator = models.ForeignKey(User, on_delete=models.CASCADE) Name = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) Status = models.CharField(max_length=9, choices=EventStatus.choices, default=EventStatus.Open) def __str__(self): return self.Speaking_Event_Name def status(self): return EventStatus.Completed if timezone.now() > self.date else self.Status I tried creating a function for it, and it does not seem to work. I am unsure if I am in the correct path or not and I have been stuck for a week. -
Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last):
please help trying to runserver and getting this error, this error starts from moving the project folder. even i try undo button. still having the same issue. is any solution to get back normal. -
The session between Django and database
I wrote the database settings of PostgreSQL in settings.py as shown below : "settings.py" DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'admin', 'HOST':'localhost', 'PORT':'5432', } } <Questions>: When starting Django server as shown below, does the session between Django and PostgreSQL start and keep connected without disconnected? kai@DESKTOP-QVRCPAL MINGW64 ~/django-project/ (main) $ python manage.py runserver 0.0.0.0:8000 Watching for file changes with StatReloader Performing system checks... When reloading Django server by changing file contents, does the session between Django and PostgreSQL disconnect and connect again? C:\Users\kai\django-project\store\views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... When stopping Django server with CTRL + C as shown below, does the session between Django and PostgreSQL disconnect? kai@DESKTOP-QVRCPAL MINGW64 ~/django-project/ (main) $ -
What is the equivalent of "success" and "complete" from jQuery to Javascript
I currently have a working solution of an ajax jquery where on success it sets an interval of a function for 1 second. On complete it clears the interval and it works perfectly fine. However, i am trying to convert this working ajax jquery to pure javascript and i am having difficulties working out how to convert "success" and "complete". What i have tried is using "onreadystatechange" and check if the ready state is equal to 4 (as the operation is done) and set the interval function and outside the if statement is to clear the interval. Doing this current method does not work as the interval keeps going on each second and i am not sure if it is because my clearInterval function is not getting used or if it is because the readystate is always at 4 so the setInterval function keeps getting run. jQuery(Working perfectly): $(document).on('submit','#post-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/sendValue/', data:{ value:$('#value').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function success(){ setInterval(displayNewValue, 1000) }, complete: function complete(){ clearInterval(success); }, }); document.getElementById('value').value = '' }); function displayNewValue(){ var test = $("#content"); test.scrollTop(test[0].scrollHeight) } Javascript: document.addEventListener('DOMContentLoaded', () =>{ const post_form = document.getElementById('post-form'); post_form.addEventListener('submit', function(event){ event.preventDefault(); let request = new XMLHttpRequest(); request.open("POST", "/sendValue/", true); … -
How do I solve this "TemplateDoesNotExist" problem
Keeping getting this error when i try running my Django application, The templates folder is inside the project folder so its on same level with app folder I have tried importing os and added os.path.join(SETTINGS_PATH, 'templates') to the TEMPLATE DIR but not working -
Django: Ajax call giving error even when everything is OK
I am using ajax to get details of variant and it is running correctly but ajax show error;As you can see in the error log, status is ok and I am receving data in responseText This is my function ajax is calling -
Django sitemap category page location not working
I made sitemap to my site but i have some problems. First problem is end of the sitemap.xml page, lots of codes in it, but how can i remove these lines. Here is my sitemap https://www.endustri.io/sitemap.xml And here is the codes which i wanna remove... And Second problem is I have category page forexample: https://www.endustri.io/kategori/makine/ When i make sitemap class like this class CategorySitemap(Sitemap): changefreq = 'weekly' priority = 0.8 def items(self): return Category.objects.all() def lastmod(self, obj): return obj.date_added In sitemap my category links be like this https://www.endustri.io/makine/ but it must be like this https://www.endustri.io/kategori/makine/ How can i fix this? Here is my model.py from django.db import models from django.contrib.auth.models import User from tinymce import models as tinymce_models from django.urls import reverse class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('detail', args=[str(self.slug)]) class Post(models.Model): category = models.ForeignKey(Category, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) intro = models.TextField() body = tinymce_models.HTMLField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) featured_photo = models.ImageField(null=True, blank=True, upload_to="blog/") date_added = models.DateTimeField(auto_now_add=True) num_reads = models.PositiveIntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('detail', args=[str(self.slug)]) And sitemaps.py from django.contrib.sitemaps import Sitemap from … -
DJANGO HTML and Python - How to display list in horizontal view with proper spacing
I am trying to make a personal website to track my list of rentals so that everywhere i go, i can view who are still not paid. (btw, i am not an IT person.. just trying to be techie and see how far i can go with it..) i have a csv file, it contains the following information. serial number, name, address, age, monthly_rent, unpaid_months, total_unpaid i am able to show it in the html, but it not aligned properly. Here's what i tried HTML `RENT {% for dt in data %} {{ dt }} {% endfor %} ` VIEWS.PY ` out = [] * 4 count = 0 rental_list = open('rent/static/rentals.txt', 'r') while True: line = rental_list.readline() if not line: break display = line.replace(',', ' ') if not count == 0: out.append(display) count += 1 rental_list.close() return render(request, 'main.html', {'data' : out})` i have two records as test. it shows like this unfortunately 0001 AAA BBB CCC DDD EEE FFF 0002 GGG HHH III JJJ KKK LLL I wanted it to be flexible, like in a specific coordinates like this when i add the headers. SN NAME ADDRESS RENT UNPAID(MOS) TOTAL UNPAID AAA. BBB CCC DDD EEE <button> If … -
nginx is returning 403 status code for non existing django static file path instead of 404
For Public Directories like /static/ and /media/ in django, if we hit non-existing path it return 403 Status instead of 404. How to get 404 for invalid static or media file paths ? E.g https://example.com/static or https://example.com/media It does return 404 if we hit it like https://example.com/static/some_random_words But i want it should return 404 for below path too https://example.com/static -
How to add allow response header to all django views?
How can I add the allow header that specifies the allowed HTTP methods to the response headers of all Django views? -
How to Secure Django Media Files in Production
In my localhost server, I was able to restrict users from accessing pdf media files which they are not supposed to access given that they are not the uploader of the file or the admin of the system. The problem is that when I tried to deploy my application, the restriction on my media files no longer works. This is my urls.py urlpatterns = [ path('media/pdf/<str:path>', views.pdf, name='pdf'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) And my MEDIA_URL and MEDIA_ROOT in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Also my debug is still set to TRUE in deployment, could this also be the problem? -
can Django listen to html events like javascript?
I have a html page with a datalist like this <input list="areas" placeholder="type option here"> <datalist id="areas"> <option>TV</option> <option>LAPTOP</option> <option>PHONE</option> </datalist> My objective is to create another list of selectable options using the information the user selected on this one, for example, if he chooses TV I'd like to either a) send a request to django and get the JsonResponse and render the next datalist using that Json. b) send a request to django and get the JsonResponse and make it return another page just like the previous but with the next data I learned that when Django renders and HTML page, I can send a context python Dict, so html has access to those variables. However, I am struggling to make the HTML call Django view functions and either render their result on the same page or open a new page with those results. I heard that HTML has some events that can be "listened" (don't know how that works) and the listener can make things happen, Javascript seems to be built exactly for this purpose since so many intuitive funtions like (onclick("makeSomething") / onchange("makeSomething")/ onhover("makeSomething")) Can I do something like this using only Django and HTML ? -
Show secondary foreign key values in the inline django admin
models.py class FarmerAdvisory(BaseModel): id = models.AutoField(db_column='id', primary_key=True) title = models.CharField(db_column='title', max_length=200, null=True, blank=True) description = models.CharField(db_column='description', max_length=750, null=True, blank=True) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, null=True, db_column='farmer_id') class Meta: verbose_name = 'Farmer Advisory' verbose_name_plural = 'Farmer Advisories' managed = True db_table = 'farmer_advisory' class ReplyFarmerAdvisory(BaseModel): reply = models.CharField(db_column='reply', max_length=750, null=True, blank=True) label = models.CharField(db_column='label', max_length=100, null=True, blank=True) farmer_advisory_id = models.ForeignKey(FarmerAdvisory, on_delete=models.CASCADE, db_column='farmer_advisory_id') objects = models.Manager() class Meta: verbose_name = 'Reply Farmer Advisory' verbose_name_plural = 'Reply Farmer Advisories' managed = True db_table = 'reply_farmer_advisory' class AdvisoryMedia(models.Model): id = models.AutoField(db_column='id', primary_key=True) farmer_advisory_id = models.ForeignKey(FarmerAdvisory, on_delete=models.CASCADE, db_column='farmer_advisory_id', null=True, blank=True) reply_farmer_advisory_id = models.ForeignKey(ReplyFarmerAdvisory, on_delete=models.CASCADE, db_column='reply_farmer_advisory_id', null=True, blank=True) farmer_media_file = models.CharField(db_column='farmer_media_file', max_length=50, null=True, blank=True) is_active = models.BooleanField(db_column='is_active', null=False, default=True) reply_media_file = models.FileField(upload_to=content_file_name, null=True, blank=True, db_column='reply_media_file') class Meta: verbose_name = 'Advisory Media' verbose_name_plural = 'Advisories Media' managed = True db_table = 'advisory_media' admin.py class AdvisoryMediaInline(NestedStackedInline): model = AdvisoryMedia extra = 0 class ReplyFarmerAdvisoryInline(NestedStackedInline): model = ReplyFarmerAdvisory extra = 1 inlines = [AdvisoryMediaInline] class FarmerAdvisoryAdmin(NestedModelAdmin): inlines = [ReplyFarmerAdvisoryInline] I want to show the fields with respect to the farmer advisory. But when i am adding fk_name = 'farmer_advisory_id' inside AdvisoryMediaInline, i am getting error stating ValueError: fk_name 'farmer_advisory_id' is not a ForeignKey to 'farmer.ReplyFarmerAdvisory'. But i want to show … -
Django throws AttributeError: 'str' object has no attribute '_meta' when trying to migrate
I'm working on a small project on my own, and I have some problems with the migrations. I managed to migrate everything well so far, but I removed a field from my models.py and now there are problems somehow. I had a field called tags that was referencing to a model from taggit, but I decided to remove this field and do it on my own, so the field tags still exists but its not referencing to the tagablemanager of taggit anymore, but on my own tag model now Nevermind everytime I excecute python manage.py migrate to make the database, this error is thrown: Applying inventory_app.0014_item_tags...Traceback (most recent call last): File "/Users/ilianhaesler/Documents/Work/inventory/inventory/manage.py", line 22, in <module> main() File "/Users/ilianhaesler/Documents/Work/inventory/inventory/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) … -
Union of non-model serializers in Django Rest Framework
Through serializers, I'm trying to describe that a field could be serialized as one of N options (similar to typing.Union). The goal of this is to use DRF Spectacular to generate Union Types. For example: From the following serializers class SerializerA(serializers.BaseSerializer): a_field = serializers.CharField() class SerializerB(serializers.BaseSerializer): b_field = serializers.CharField() I want to describe: class CombinedSerializer(serializers.BaseSerializer): combined_field = <either_serializerA_or_serializerB> Which, through DRF spectacular, I would be able to generate into export interface SerializerA = { a_field: string; } export interface SerializerB = { b_field: string; } export interface CombinedSerializer = { combined_field: SerializerA | SerializerB } I've looked into https://github.com/denisorehovsky/django-rest-polymorphic but that seems to support model serializers. https://github.com/tfranzel/drf-spectacular/issues/382 also doesn't seem to support this use case - any suggestions? -
Submit button is not working in html using django
HTML FILE in html page action is not added i wanted to know how i can submit the form without adding action attribute?? -
How to share memory using gunicorn+uvicorn workers or Daphne+supervisor
I have a Django web application that uses Daphne web server. I have a problem when running multiple instances of app using supervisor (that corresponds to running app with multiple uvicorn workers using gunicorn). I tried to solve it by sharing memory using Redis DB to save user instances so that every worker can access logged in users but then I came across the problem. There is threading inside of User class and I can't pickle _thread.lock object so I can't use Redis. If I separate threading from my User class, I don't profit from it at all because then worker has to do same job again, that is, make a thread, when I send request. Is there a workaround to this problem? I.e. using internal shared memory or something like that? -
Validating several objects at once, before saving
Is it possible to sum values in fields of several objects? class MyModel(model.Models): name = models.Charfield() amount = models.IntegerField() Model Object 1 Object 2 Object 3 Object 4 Object 5 Here i want the sum of "amount" in all the objects to use in my validation. If the total "amount" is correct, i want to save all objects. How do i do this?