Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No apps folder on django lightsail
After creating a new lightsail django instance on AWS, I found that the folders /opt/bitnami/apps/ does not exist as referenced in the documentation https://aws.amazon.com/getting-started/hands-on/deploy-python-application/. I've created django instances before on AWS and have never encountered this issue. bitnami@ip-172-26-4-185:~$ ls bitnami_application_password bitnami_credentials htdocs stack bitnami@ip-172-26-4-185:~$ cd / bitnami@ip-172-26-4-185:/$ cd opt bitnami@ip-172-26-4-185:/opt$ cd bitnami bitnami@ip-172-26-4-185:/opt/bitnami$ cd apps -bash: cd: apps: No such file or directory bitnami@ip-172-26-4-185:/opt/bitnami$ ls apache bncert-tool bnsupport-tool git nami properties.ini stats apache2 bnsupport common gonit node python var bncert bnsupport-regex.ini ctlscript.sh mariadb postgresql scripts Additional info: 16 GB RAM, 4 vCPUs, 320 GB SSD Django Virginia, Zone A (us-east-1a) attached static ip address -
ImportError: path_to_venv/lib/python2.7/site-packages/PIL/_imaging.so: undefined symbol: PyString_FromStringAndSize
[Tue Sep 01 10:36:25.566741 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] Traceback (most recent call last): [Tue Sep 01 10:36:25.566824 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/fairy/wsgi.py", line 19, in <module> [Tue Sep 01 10:36:25.566872 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] application = get_wsgi_application() [Tue Sep 01 10:36:25.566911 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/jielong_env/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application [Tue Sep 01 10:36:25.566946 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] django.setup() [Tue Sep 01 10:36:25.566984 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/jielong_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup [Tue Sep 01 10:36:25.567019 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] apps.populate(settings.INSTALLED_APPS) [Tue Sep 01 10:36:25.567056 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/jielong_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate [Tue Sep 01 10:36:25.567090 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] app_config.import_models(all_models) [Tue Sep 01 10:36:25.567128 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/jielong_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models [Tue Sep 01 10:36:25.567184 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] self.models_module = import_module(models_module_name) [Tue Sep 01 10:36:25.567223 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module [Tue Sep 01 10:36:25.567257 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] return _bootstrap._gcd_import(name[level:], package, level) [Tue Sep 01 … -
listview objects are not redirecting to detailview when clicked
i am trying to create a blog , i am able to display list of objects in my blog model by class based list view.. but when trying to display them individually by function based detail view i am getting 404 error. (The current path, blog/1, didn't match any of these.) i tried class based views as well but unfortunately got no success.. please see.. models.py from django.db import models import datetime # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) def __str__(self): return self.title views.py from django.views.generic import ListView , DetailView , UpdateView from.models import BlogPost class BlogList(ListView): model = BlogPost template_name = 'blog/bloglist.html' context_object_name = 'post' def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) context = {'blg': blg, } return render(request, 'blog/blogdetail.html', context) urls.py from django.urls import path # importing views from views..py from .views import BlogList ,detailview urlpatterns = [ path('list', BlogList.as_view(), name='list'), path('(?P<id>\d+)/$', detailview, name='detail') ] bloglist.html <div class="post-body"> {% for p in posts %} <a href="/blog/{{ p.id }}"><blockquote>{{p}}</br></br>{{p.Date}}</blockquote> </a> {% endfor %} -
Sending Emails in Production Environment
I have a web app I'm hosting on Digital ocean using nginx and gunicorn. I recently tried to add password reset capabilities for my users as well as a contact form. When I ran and tested on my local machine everything worked fine, but now that I've moved to production I get a 500 error when I try to send a password reset email, and my contact form is not generating any email message. Is there some additional set up related to digital ocean, or nginx that needs to be done to allow emails to be sent? my settings.py is set up as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'admin@programaticlearning.com' EMAIL_HOST_PASSWORD = 'CorrectPassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
How to getting results of bulk creating user without waiting for a long time?
I want to generate lots of users in admin system. But the question is make_password in Django is a time-consuming operation. So, i want to assign this operation to a thread. Thus, the admin can get the generated file immediately without waiting for a long time which including user id, password. Below is the code i wrote which have some issues. Cause for getting the new generated user id, I consider the lastest user id plus by one as the beginning id, and getting the end user id by adding the beginning id by the num to generate. Then, if someone is registering during the period of bulk creating by admin, errors like dulplicate entry will throw. How should i address this problem, pls give me some advice. Thx. def BatchCreateUser(self, request, context): """批量创建用户""" num = request.get('num') pwd = request.get('pwd') pwd_length = request.get('pwd_length') or 10 app = request.get('app') latest_user = UserAuthModel.objects.latest('id') start_user_id = latest_user.id + 1 # 起始学号 end_user_id = latest_user.id + num # 终止学号 user_id_list = [i for i in range(start_user_id, end_user_id + 1)] # 学号列表 if not pwd: raw_passwords = generate_cdkey(num, pwd_length, False) # 随机生成密码列表 Thread(target=batch_create_user, args=(user_id_list, raw_passwords, app)).start() else: raw_passwords = [pwd for _ in range(num)] Thread(target=batch_create_user, … -
Wagtail Admin: How to control where user is redirected after submitting changes for moderation
On a Wagtail site I've built, I have a model type that is editable by authenticated users who do not have full admin privileges. They can only save as a draft or submit the changes for moderation. The problem I'm having is that Wagtail is inconsistent about where it redirects after executing these two actions. Saving the Draft takes the user back to the edit screen they were just on, with a note saying the draft was saved (good). Submitting for Moderation returns the user to the admin browse view of the parent page, which shows all of the sibling nodes in a list. They can't edit the vast majority of items on that list, so I think this is confusing for a non-admin user. I would like to have the "Submit for Moderation" action detect whether the user belongs to a group other than admin (or, failing that, whether the page has unpublished changes, as in my code example below) and, if so, redirect them back to the edit screen just like "Save as Draft" does. I tried this in my model definition and it didn't work: def save(self, *args, **kwargs): #do some field value manipulations here before saving … -
Django: manage.py runserver fails with watchman exception
When I try running manage.py runserver on a completely new project, I get a watchman exception: (towngen) gru-mbp:towngenweb gru$ ./manage.py runserver Watching for file changes with WatchmanReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. September 01, 2020 - 01:07:15 Django version 3.1, using settings 'towngenweb.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 613, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 598, in start_django reloader.run(django_main_thread) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 313, in run self.run_loop() File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 319, in run_loop next(ticker) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 532, in tick self.update_watches() File … -
Django - Best Approach to query latest time series objects?
Long time lurker, first time poster, so beware! Let's say I'm modeling end of day stock prices, and have two Django models for this: Stock, and DailyPriceData (simplified for this question). In reality, Stock has additional metadata, and DailyPriceData has OHLC data, volume, etc.: class Stock(models.Model): ticker = models.CharField(max_length=10) class Meta: unique_together=['ticker'] class DailyPriceData(models.Model): stock= models.ForeignKey(Stock, on_delete=models.CASCADE) date = models.DateField() price = models.DecimalField(max_digits=30, decimal_places=6) class Meta: unique_together=['stock','date'] indexes = [ models.Index(fields=['stock','date']), ] Now, let's say there are 50k Stock objects, and each Stock object has ~10 years or more of DailyPriceData objects. What is the best way of extracting only the latest DailyPriceData objects of each Stock object for display on a frontend? Using PostgreSQL, I can accomplish the task with the .Distinct method, though this is very slow and not suitable for a frontend. Should I create another model object, shown below? Is this wasteful? Should I use a signal or management command to keep this updated?: class DailyPriceDataLatest(models.Model): stock= models.OneToOneField(Stock, on_delete=models.CASCADE) daily_price_data = models.OneToOneField(DailyPriceData, on_delete=models.CASCADE) class Meta: unique_together = ['stock'] Is there a better way to skin this cat, so that I can query the latest price data by Stock or group of Stock objects quickly? -
How can I to link my post creator page to the other pages in Python?
one of my html files about.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static "all.css" %}"> <link rel="stylesheet" href="{% static "bootstrap.css" %}" > <link rel="stylesheet" href="{%static "style.css" %}"> <title>Online yuridik xizmatlar</title> </head> <body> <nav class="navbar navbar-expand-sm navbar-dark bg-dark"> <div class="container"> <a href="{% url 'home' %}" class="navbar-brand"><i class="fas fa-balance-scale"></i></a> <button class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a href="{% url 'home' %}" class="nav-link">Bosh sahifa</a> </li> <li class="nav-item"> <a href="{% url 'about' %}" class="nav-link">Biz haqimizda</a> </li> <li class="nav-item"> <a href="{% url 'index' %}" class="nav-link">Blog</a> </li> <li class="nav-item"> <a href="{% url 'contact' %}" class="nav-link">Biz bilan bog'laning</a> </li> </ul> </div> </div> </nav> <div class="about-banner"> <div class="container text-center py-5 text-white"> <h1>Bizning kompaniyamiz haqida</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis aut doloribus dolores minus</br> voluptatibus in?</p> </div> </div> <div class="about-content"> <div class="container"> <div class="row py-5"> <div class="col-md-6"> <h3>What we do</h3> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolorem, doloremque quidem quasi sint reiciendis rem voluptas atque ab nam non, qui excepturi unde optio cum, omnis necessitatibus recusandae a repellat.</p> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolorem, doloremque quidem … -
Allow download of entire contents of Amazon S3 folder in Django
I'm using Django and I have a S3 Account with files in a folder called media. I want to allow users to download the entire list of files as an archived zip folder to save them having to click on each individual link to get the file. I'm using Django, and Amazon S3 and Boto3. Links are like, https://mydomain.s3.amazonaws.com/media/filename1.txt https://mydomain.s3.amazonaws.com/media/filename2.txt https://mydomain.s3.amazonaws.com/media/filename3.txt https://mydomain.s3.amazonaws.com/media/filename4.txt https://mydomain.s3.amazonaws.com/media/filename5.txt So essential I want to bundle all files in another link that is a download to all files, as an archive. Any suggestions on how to do this with Django? -
Django testing hangs with --keepdb flag
For performance tuning reasons, I want to run Django tests against a copy of my production database. As I understand it, this should be possible by: (1) adjusting Django settings like DATABASES = { 'default': { ... 'TEST': { 'NAME': 'my_database_copy', }, } } and (2) using the --keepdb flag, as in python manage.py test --keepdb.[1] But when I do this, the process hangs, looking like this: bash-4.2$ python manage.py test --keepdb Using existing test database for alias 'default'... (The process won't close with ctrl+c. I'm using Docker, and I stop it by restarting Docker.) There are no unapplied migrations for the database, and the test command (python manage.py test) works fine, if --keepdb is omitted. I confirmed that the database copy is properly restored and accessible because I can access it when I run python manage.py shell. [1] https://docs.djangoproject.com/en/3.1/topics/testing/overview/#preserving-the-test-database -
Line number: 1 - 'id
Estoy intentando importar y exportar registros desde el admin de django y si me exporta el archivo pero cuando abro el archivo estA en blanco a pesar de que hay registros en los datos del modelo que quiero exportar Y cuando quiero importar me aparece esto: Line number: 1 - 'id' Traceback (most recent call last): File "c:\PYTHON\DJANGO\Truelogisticinc\.env\lib\site-packages\import_export\resources.py", line 639, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "c:\PYTHON\DJANGO\Truelogisticinc\.env\lib\site-packages\import_export\resources.py", line 334, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "c:\PYTHON\DJANGO\Truelogisticinc\.env\lib\site-packages\import_export\resources.py", line 321, in get_instance import_id_fields = [ File "c:\PYTHON\DJANGO\Truelogisticinc\.env\lib\site-packages\import_export\resources.py", line 322, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' model.py # DJANGO from django.db import models # Models from django.contrib.auth.models import User from users.models import Profile from records.models import Customers, Origins, Airlines, Warehouse, Grades, Products #from auth.models import user # Create your models here. class PackingLists(models.Model): #Packing Lists models.''' #Registers number_lote = models.CharField(max_length=45) order_date = models.DateField(auto_now_add=True) #Descriptions ship_date = models.DateField() awb_number = models.CharField(max_length=45, null=True, blank=True) id_fish = models.IntegerField() box_number = models.IntegerField() product = models.ManyToManyField(Products) weight = models.FloatField() size = models.CharField(max_length=20) origin = models.ForeignKey(Origins, on_delete=models.CASCADE, null=False, blank=False, related_name='pls_origins') ship_via = models.ForeignKey(Airlines, on_delete=models.CASCADE, null=False, blank=False, related_name='pls_shipsvia') warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, null=False, blank=False, related_name='pls_warehouses') grade = models.ForeignKey(Grades, on_delete=models.CASCADE, null=True, blank=True, related_name='pls_grades') #user = … -
How to run django through pypy?
(venv) PS E:\trydjango\myblog> pypy3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\pypy3.6-v7.3.1-win32\site-packages\django\db\backends\sqlite3\base.py", line 67, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.6.21). -
how do i solve problem of receiver django?
i use two reciver but one of them is worked i dont now whats problem (Create_QueueSendProject reciver is worked but Create_QueueSendProject not work ) class Category(models.Model): title = models.CharField(max_length=254) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Category' def __str__(self): return str(self.title) class Project(models.Model): def get_upload_path(self, filename): return "{}/project_file/{}/{}".format(self.user.id,"prjid_"+self.id,filename) confirmation_choices = ( (ProjectConfirmationStatus.REJECTED, "Rejected"), (ProjectConfirmationStatus.ACCEPTED, "Accepted"), (ProjectConfirmationStatus.PENDING, "Pending") ) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) body = models.TextField (blank=False, null=False) file = models.FileField(upload_to=get_upload_path,max_length=254,null=True, blank=True,) category = models.ManyToManyField(Category, blank=True) confirmation_status = models.CharField(max_length=1, choices=confirmation_choices, default=ProjectConfirmationStatus.PENDING) description = models.TextField(default=None,blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['creation_date'] db_table = 'Projects' def __str__(self): return 'id:{}-{}'.format(self.id,self.body[0:20]) class QueueSendProject(models.Model): project = models.OneToOneField(Project,on_delete=models.CASCADE) is_send = models.BooleanField(default=False) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Queue_send_projects' def __str__(self): return str(self.id) @receiver(post_save, sender=QueueSendProject) def Create_QueueSendProject(sender, instance, created, **kwargs): """send project in chanel telegram """ # import pdb; pdb.set_trace() if created : print("yessssssssss")#Not work instance.is_send=True instance.save() @receiver(post_save, sender=Project) def Create_QueueSendProject(sender, instance, created, **kwargs): """create QueueSendProject for project if confirmation_status update to ACCEPTED""" # import pdb; pdb.set_trace() if not created : if instance.confirmation_status==ProjectConfirmationStatus.ACCEPTED: queuesend_obj = QueueSendProject.objects.update_or_create(project=instance) -
How to migrate local Django model changes to production?
I'm attempting to migrate my local changes to my public production site Django site. The problem I am having is my local changes overwrite my production models, when I upload my local changes to production. Is their a way to merge my changes without totally ruining my production models. Is there a library that I can use that will better help me manage conflicts between the two code bases? -
get_queryset does not affect querying in django rest framework ModelViewSet
My ViewSet looks like this: class ClientViewSet(viewsets.ModelViewSet): queryset = models.Client.objects.all() serializer_class = serializers.ClientSerializer def filter_queryset(self, queryset): return models.Client.objects.filter(**self.request.data) def get_queryset(self): return models.Client.objects.filter(owner=self.request.user) The model looks like this: class Client(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.id) So, I'm trying to filter clients so that only the current user's clients are presented to them. However, GET api/clients still returns all the clients of all users. What have I done wrong? -
moduleNotFoundError: No module named 'booktime.main'
following a book, I created a django project named booktime then an app named main. as I try importing files within the app such as forms.py as in from main import forms the names main and forms are red-underlined, though works in some cases as in views.py where the server runs still but on running tests file I get no module named 'booktime.main' error -
How to use variables tag from Django in HTML ids
My issue is actually quite simple and I'm not sure that there is an answer to it but still. I'm trying to reduce some image rendering that is hardcoded into my HTML template by making a simple for loop that Django provides with a dict comprehension. Actually everything is working in my project even if the "id" is not equal to the value "for" of my label. Here are my code and a screenshot of it that in lights far better my issue that the whole code. <div class="form-check"> {% for data in images %} <input class="form-check-input invisible" type="radio" name="image" id="{{ data }}" value="media/{{ data }}" > <button type="button" class="btn btn-outline-success"><label class="form-check-label" for="{{ data }}"> <img class="rounded-circle account-img" src="media/{{ data }}" width="120" height="120"> </label></button> {% endfor %} <input class="form-check-input invisible" type="radio" name="image" id="Profil1.png" value='media/Profil1.png' > <button type="button" class="btn btn-outline-success"><label class="form-check-label" for="Profil1.png"> <img class="rounded-circle account-img" src="{{ "media/Profil1.png" }}" width="120" height="120"> </label></button> <input class="form-check-input invisible" type="radio" name="image" id="Profil2.png" value='media/Profil2.png' > <button type="button" class="btn btn-outline-success"><label class="form-check-label" for="Profil2.png"> <img class="rounded-circle account-img" src="{{ "media/Profil2.png" }}" width="120" height="120"> </label></button> <input class="form-check-input invisible" type="radio" name="image" id="Profil3.png" value='media/Profil3.png' > <button type="button" class="btn btn-outline-success"><label class="form-check-label" for="Profil3.png"> <img class="rounded-circle account-img" src="{{ "media/Profil3.png" }}" width="120" height="120"> </label></button> <input class="form-check-input invisible" type="radio" … -
{"detail":"Not found."} It could like comments but it couldn't like the replies
I have a problem on my project. I am trying to solve it all the day today but no luck. I am trying to make a POST-COMMENT-LIKE blog. The LIKE system works pretty well on Posts and Comments but it break when i am trying to like the replies of the comments. When i trying to like the reply it shown the message {"detail":"Not found."}. Any help for this?? Thank you!! :) The models.py: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE) comment_like = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='comment_like') content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def children(self): return Comment.objects.filter(parent=self) def get_api_url(self): return reverse("comments-api:thread", kwargs={"pk": self.pk}) def get_comment_like_url(self): return reverse("comments-api:comment-like-toggle", kwargs={"pk": self.pk}) # def get_content_type(self): # instance = self # content_type = ContentType.objects.get_for_model(instance.__class__) # return content_type @property def is_parent(self): if self.parent is not None: return False return True The serializers.py : class CommentDetailSerializer(ModelSerializer): user = UserDetailSerializer(read_only=True) reply_count = SerializerMethodField() content_object_url = SerializerMethodField() replies = SerializerMethodField() comment_like = SerializerMethodField() comment_like_by = SerializerMethodField() class Meta: model = Comment fields = [ 'id', 'user', #'content_type', #'object_id', 'content', 'reply_count', 'replies', 'timestamp', 'content_object_url', 'comment_like', 'comment_like_by', ] read_only_fields = [ … -
Django :app is not a registered namespace
I am very new to Django and want to know the reason behind the error "No Reverse Match" in my app.Also want to know why it was telling namespace is not registered? -
I have confusion adding/linking HTML multiple pages to my Django website
I am new to Django web development. I have successfully created an index.html page and it viewed on 127.0.0.1:8000 successfully. But the problem now is I have to link multiple pages, for example an about and contact section. I created about.html and contact.html pages in the same directory where my index.html page is. But when i click on about or contact page, it is not showing. How can I link these pages to my website? -
Django ORM: Bulk Create : More than one sql query
In the django documentation it is mentioned that bulk create generally executes one query This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are) django documentation What are the scenarios in which django will create more than one query and are these queries executed atomically. -
Django ImageField has no url attribure associated with it
I'm trying to create a one page app where you can upload a picture to the database and it would display it in the index page. I can't get the photo to display, even though when calling in the html part {{post.picture}} it returns the path of the picture media settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' view: from random_tasks_app import forms from random_tasks_app.models import Post def index(request): posts = Post.objects.all() if request.method == 'POST': form = forms.UploadImageForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = forms.UploadImageForm() return render(request, 'index.html', {'form': form, 'posts' : posts}) models: from django.db import models class Post(models.Model): picture = models.ImageField(upload_to='photos/', blank=True, null=True) forms: from django.forms import ModelForm from random_tasks_app.models import Post class UploadImageForm(ModelForm): class Meta(): model = Post fields = '__all__' html file: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <form method = "POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {%for post in posts%} <img src="{{ hotel.picture.url }}"/> {%endfor%} </body> </html> The error: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) ValueError: The 'picture' attribute has no file associated with it. thanks. -
Django open link which does pre-set things (click "men" on e-ccomerce site and have it automatically filter on men's clothing
Sorry about the rubbish title, I wasn't sure what to put, if anyone has any improvements, please comment and I will update accordingly. Problem I currently am working on an e-commerce website, and have finished setting up the shop section (where you can view products and filter based on your needs), now on the navbar and other locations, I have names such as "Men" or "Women", What I need is that these links go to the shop page and automatically filter based on the link So if I click "men", it should go to the shop page, and return back the items already filtered showing men's products (preferably all the options inside of the men category should already be ticked, but this is not necessary). Then you can carry on adjusting your filter as required as if you clicked on the shop page directly. Soulutions Tried First of all, I tried to set up a system where you can use a dynamic URL to see the link coming from, for example, "shop/women", but this would need be exactly the same as "shop/" just with the filtering, I tried to add this into my urls.py file like this path('shop/<str:category>', Shop.as_view(), name="shop"), … -
Django Rest Framework: How to ignore 'unique' primary key constraint when validating a serializer?
I am attempting to store large amounts of transit data in a PostgreSQL database, where a client uploads multiple records at a time (in the tens of thousands). I only want one arrival time per stop, per route, per trip and the unique identifier for that stop, route, and trip is the primary key for my table (and a foreign key in a different table). I am trying use Django's update_or_create in my serializer to either create the entry for that arrival time or update the arrival time with the latest data if it already exists. Unfortunately, while calling is_valid() on my serializer, it identifies that the repeat records violate the uniqueness constraint of the primary keys (which makes sense), giving me this error message: 'real_id': [ErrorDetail(string='actual with this real id already exists.', code='unique')] I want to override this behavior since if the primary key isn't unique it will just update the entry. I have already tried looping over and removing validators like so: def run_validators(self, value): for validator in self.validators: self.validators.remove(validator) super(ActualSerializer, self).run_validators(value) I have also tried removing all validators using the extra_kwargs field of my serializer Meta class like so: extra_kwargs = { 'name': {'validators': []} } I …