Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I program a dynamic sitemap in django, mine not working
The static part works fine but the dynamic posts of my blog app are not generated from django.contrib.sitemaps import Sitemap from django.urls import reverse from .models import Post class PostSitemap(Sitemap): changefreq = "weekly" priority = 0.9 def items(self): return Post.objects.all() I'm not able to get a dynamic sitemap with my blog and my Post class in models: class Post(models.Model): title=models.CharField(max_length=100) header_image = models.ImageField(null=True , blank=True, upload_to="images/") title_tag=models.CharField(max_length=100) author= models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextUploadingField(extra_plugins= ['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')]) #body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=50, default='uncategorized') snippet = models.CharField(max_length=200) likes = models.ManyToManyField(User, blank=True, related_name='blog_posts') def total_likes(self): return self.likes.count() class Meta: verbose_name = "Entrada" verbose_name_plural = "Entradas" ordering = ['-post_date'] def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('home') If any one can help me I would be very grateful. urls.py: from django.contrib.sitemaps.views import sitemap from theblog.sitemaps import PostSitemap, StaticSitemap sitemaps = {'static': StaticSitemap, 'blog': PostSitemap} -
Django count object views on a practically and fair base
I was searching for a solution to practically and fair track views/hit's of my post elements. Sadly all solutions I found where based on the users IP or Session-Key. In practices such a solution can be used but is somehow also very stupid I guess. All these information are coming from the client directly and can be faked either be logging-in again and get a new session key or using a proxy/VPN etc... There are several automatons to accomplish such a task at scale, see how the music industry, especially spotify gets frauded by such attacks. My Idea now is to temporary bound a view/hit to the user for at least 24 hrs. After time has went by, the table gets cleared out by celery as a periodical task. Before deleting the temporary user counted hit, celery syncs all hits to the actual post object, as this is just a IntegerField I can count-up using '+=' A model for this could look like this: class Hit(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=hit_post_models, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') viewer = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) Now I'm at the point to get a bit confused by the actual counting implementation. … -
how to get parent object from child object in python
I have two models(classes) that one inherits from another. GRESubjectCertificate as parent class GRESubjectCertificate(LanguageCertificate): quantitative = models.PositiveSmallIntegerField() verbal = models.PositiveSmallIntegerField() analytical_writing = models.DecimalField( max_digits=2, decimal_places=1, ) total = models.PositiveSmallIntegerField() and GREBiologyCertitficate as child: class GREBiologyCertificate(GRESubjectCertificate): cellular_and_molecular = models.PositiveSmallIntegerField() organismal = models.PositiveSmallIntegerField() ecology_and_evolution = models.PositiveSmallIntegerField() I want to cast an object from GREBiologyCertificate to GRESubjectCertificate by parent class name in lower but it does not work. I have used before this solution to convert child object to parent object but now it fails. instance1 = GREBiologyCertificate() instance2 = instance1.gresubjectcertificate 'GREBiologyCertificate' object has no attribute 'gresubjectcertificate' -
Got a 500 HTTP ERROR uploading image django-CKEDITOR
Using Django 3.1 and ckeditor 6.0.0 and standard django debug server. I get 500 http error when I upload an image through RichTextUploadingField() My urls.py: from django.contrib import admin from django.urls import path, include from filebrowser.sites import site from django.conf import settings from django.views.static import serve from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('ntgiapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Key part of settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'ntgiapp/static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'ntgiapp/media') CKEDITOR_UPLOAD_PATH = "" CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename' CKEDITOR_IMAGE_BACKEND = 'Pillow' -
view must be a callable or a list/tuple in the case of include() | Class-based views error
I don't know why, but I got this weird error, view must be a callable or a list/tuple in the case of include(). This is my views.py: class HelloWorldView(View): def get(self, request, *args, **kwargs): context=[ ] return render(request, 'main.html', context) and my urls: urlpatterns = [ path('', HelloWorldView.as_view(), name='helloWorld'), ] -
Content of database not showing up in Django
I have some problems to get the content out of the django database. I'm a bloody beginner at django so I did some tutorials. They've worked fine. Now I want to reproduce them in my own project with own variables so I can see if I've understood all the stuff. So to come to my problem I initalized my modules in models.py from django.db import models class Aboutme(models.Model): author = models.CharField(max_length=30) ... This works because I could add content to the database. So there is no mistake. Now in the views.py from django.shortcuts import render from portfolio.models import Aboutme def portfolio_index(request): aboutme = Aboutme.objects.all() context = {'aboutme': aboutme} return render(request, 'portfolio_index.html', context) So finally in my HTML file, called portfolio_index.html, I call the content via <h1>{{ aboutme.author }}</h1> I guess it's right. But the content of author doesn't showup, so what did I miss? I can call static files via django, so couldn't be something wrong with django... Can anyone help. Thanks in advance. -
Passing model database metric to view
I am creating a Django app that displays a certain number of buttons (called tables). Below are my files: model.py class Table(models.Model): id_num = models.IntegerField(verbose_name="Table Number", db_index=True) slug = models.SlugField(max_length=200, db_index=True) max_guest_num = models.IntegerField(verbose_name="Max Number of Guests", default=0) description = models.TextField(verbose_name="Table Note", blank=True) available = models.BooleanField(verbose_name="Availability", default=True) last_checkin_time = models.DateTimeField(verbose_name="Checkin Time") last_checkout_time = models.DateTimeField(verbose_name="Checkout Time") created = models.DateTimeField(verbose_name="Date of creation", auto_now_add=True) updated = models.DateTimeField(verbose_name="Last Updated", auto_now=True) admin.py @admin.register(Table) class TableAdmin(admin.ModelAdmin): list_display = ['id_num', 'slug', 'max_guest_num', 'available', 'created', 'updated'] view.py from django.http import HttpResponse from django.shortcuts import render def table_view(request): return render(request, 'tables/table_view.html', {'table_num': '???'}) table_view.htlm (template) {% extends "base.html" %} {% block title %}Dashboard{% endblock %} {% block content %} <h1>Table View</h1> <div id="table_display"> <button class="button table1">Table 1</button> <button class="button table2">Table 2</button> <button class="button table3">Table 3</button> <button class="button table4">Table 4</button> <button class="button table5">Table 5</button> </div> {% endblock %} I have two questions: 1 - In the template, I would like create the number of buttons based on the number of table instances created in the database. How do I retrieve and pass this variable into the view.py (this is the right place to pass into, I guess?) 2 - In the template, what is the best way to create these … -
How to create file downloading link without leaking the address of file in Django
This might perhaps be a simple question, but I somehow just can not find the solution. I am trying to develop a website using Django where a user uploads an mp3 file and then requests to process their uploaded file. I perform some processes on users' uploaded mp3 file and then provide them a demo of the result (a demo.mp3 file). So, they can download the demo of their result for free. After paying, they'll be able to download the full version of the processed mp3 file (full.mp3 file). I produce and store the demo and the full version of the results at the same time (as a user submits a request). I do not want users to be able to access the full.mp3 file unless they have paid. Currently, I create two random strings of 32 characters for each user's request. I store these strings in the Django model (dir_code and demo_dir_code fields as shown below) and then create two directories on the server (within the MEDIA_ROOT directory) with the name of these strings. class Request(models.Model): dir_code = models.CharField(max_length=32, null=False, blank=False, default='') demo_dir_code = models.CharField(max_length=32, null=True, blank=True, default='') ... In one of these directories, I put the results of … -
Django Gunicorn Nginx Worker TIMEOUT Upstream TIMED OUT ERROR
I've a web application running on Django, Gunicorn and Nginx on Azure Ubuntu VM server. When running a longer requests, the request times out and goes to 504/502 timed out error. I've tried changing timeout options in both Nginx and GUnicorn config, but didn't work. Below are my config files, Nginx.conf server { listen 80; server_name 0.0.0.0; location /static { alias /home/rootadmin/WeIntelli/static; } location / { proxy_pass http://unix:/home/rootadmin/WeIntelli/WeIntelli.sock; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 900; proxy_send_timeout 900; proxy_read_timeout 900; proxy_buffers 32 4k; } } Supervisor.conf [program:WeatherIntelligence] directory=/home/rootadmin/WeIntelli command=/home/rootadmin/WeIntelli/venv/bin/gunicorn --log-level=debug --workers=5 --timeout=600 --keep-alive=600 --worker-class=gthread --threads=3 --bind unix:/home/rootadmin/WeIntelli/WeIntelli.sock WeIntelli.wsgi:application user=rootadmin autostart=true autorestart=true stopasgroup=true killasgroup=true stderr_logfile=/home/rootadmin/WeIntelli/WeIntelli.err.log stdout_logfile=/home/rootadmin/WeIntelli/WeIntelli.out.log Request you to please help me resolve this, thanks in advance. -
TemplateDoesNotExist at /home/ entries/index.html, entries/entry_list.html
I need an extra pair of eyes, I just cannot see the mistake, below you can see all the necessary files, I think the error comes from there views.py from django.shortcuts import render from django.views.generic import ListView from .models import Entry class HomeView(ListView): model = Entry template_name='entries/index.html' urls.py from .views import HomeView from django.urls import path urlpatterns = [ path('home/', HomeView.as_view(), name='blog-home') ] base urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('entries.urls')) ] -
Heroku release fails on Key Error: 'user' for established Django project
After minor edits to the database (SQLite) and a revision number in settings.py I tried to push the changes to Heroku, which initially declared that their were unpulled files; this made no sense as this is my private project and a similar update worked two days before. The pull allowed a "git push heroku master". The code would run and attempt to deploy but return the following error block: ============ Operations to perform: Apply all migrations: admin, auth, brg_calcs, contenttypes, glossary, sessions, users Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 201, in handle pre_migrate_state = executor._create_project_state(with_applied_migrations=True) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/executor.py", line 79, in _create_project_state migration.mutate_state(state, preserve=False) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/migration.py", line 87, in mutate_state operation.state_forwards(self.app_label, new_state) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 158, in state_forwards old_field = model_state.fields.pop(self.name) KeyError: 'user' After this error, I tried re-loading the program on my laptop from GitHub. Same error. I have run "makemigrations" and "migrate", … -
Django: Store a CSS class in database
So I made an HTML button and on clicking to it, a CSS class is added to it using some Jquery/javascript logic. Is there any way I can store this animation on my database so that on page refresh the class should still stay. Or if I can do that with Javascript. A little guidance would be appreciated. Regards Fanceh -
What is an effective way to bulk create objects with related objects in django?
I have the following models: class LocationPoint(models.Model): latitude = models.DecimalField(max_digits=16, decimal_places=12) longitude = models.DecimalField(max_digits=16, decimal_places=12) class Meta: unique_together = ( ('latitude', 'longitude',), ) class GeoLogEntry(models.Model): device = models.ForeignKey(Device, on_delete=models.PROTECT) location_point = models.ForeignKey(LocationPoint, on_delete=models.PROTECT) recorded_at = models.DateTimeField(db_index=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) I have lots of incoming records to create (probably thousands at once). Currently I create them like this: # Simplified map function contents (removed mapping from dict as it's unrelated to the question topic points_models = map(lambda point: LocationPoint(latitude=latitude, longitude=longitude), points) LocationPoint.objects.bulk_create( points_models, ignore_conflicts=True ) # Simplified map function contents (removed mapping from dict as it's unrelated to the question topic geo_log_entries = map( lambda log_entry: GeoLogEntry(device=device, location_point=LocationPoint.objects.get(latitude=latitude, longitude=longitude), recorded_at=log_entry.recorded_at), log_entries ) GeoLogEntry.objects.bulk_create(geo_log_entries, ignore_conflicts=True) But I think it's not very effective because it runs N SELECT queries for N records. Is there a better way to do that? I use Python 3.9, Django 3.1.2 and PostgreSQL 12.4. -
How can i create swager document for django api?
there is FBV in Django and it log_in and when i use swagger ..it did not create input in document. """ @api_view(['POST']) def log_in(request): """ description: This API deletes/uninstalls a device. parameters: - name: username type: string required: true location: body """ payload = json.loads(request.body) phone = payload.get('username', None) user_type = payload.get('user_type', None) """ -
CSS not loading wrong MIME type on django and next.js
I am having an issue with NextJs and django. On the djnago side, when I run the server I get the mime css error. Any help? -
Getting foreign key values from Django values()
I am getting data objects from Django models using tabledata=Entity.objects.filter(quarter=1) Using this method, I am able to extract the values of the objects specified by the foreign key like so tabledata[0].creator.name However when I changed the code to tabledata=Entity.objects.filter(quarter=1).values() I can extract only foreign key values but not the values of the object data linked with the foreign key. Something like tabledata[0][creator][name] does not work Is there a way to extract the values this way? -
Downlodable pdf files in django
i am developing a web page where users should able to download a PDF forms or file.is it possible in Django, like normal HTML? i have tried bit it's not working for me. thank you in advance. here is my modle class Notice(models.Model): SL_no= models.IntegerField() Description = models.TextField() Date = models.DateTimeField(default=timezone.now) File = models.FileField(upload_to='files') -
Is it considered good practice using too many factories in pytest?
I am trying to write tests for Django/DjangoREST project. I have decided to use pytest. I have poor experience in writing tests for Django projects specifically. So I am confused now. Here is an example: @pytest.mark.django_db def test_some_view( api_client, simple_user, model1_factory, model2_factory, ... # many other model factories modelN_factory ): # ... # creating here other objects that really depends on each other # ... model2_obj = ... # model2 object on its own side depends on model3, model4... and so on model1_objs = [] for i in range(10): model1_objs.append(model1_factory(some_field=100, some_model2_rel=model2_obj) assert len(model1_objs) == 1, "Created items with duplicate `some_field`" As you can see I have too many factories to be used in one test. But looking at my model structure right now, I can't think of a better way. Is it ok to use so many factories for one test? Or should I find some issues related to my tables' relations? Any help is appreciated. Thanks in advance -
Have problem to auto create profile after register new user in django the error show this 'Manager' object has no attribute 'created'
Django show AttributeError at /ezz/register/ (this is my url) 'Manager' object has no attribute 'created' signals.py files from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.created(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() apps.py file from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals -
Django password_change gives an error on Heroku but not on localhost
I deployed my Django app on Heroku. I'm using the default password_change route from Django admin to allow the users to change their password but the problem is that whenever I go to change the password I get the following error "Connection closed without response". If I go and change a password on localhost then it works. -
How to correctly configure for page refresh with Vuejs frontend served by nginx proxying to gunicorn + django?
I have a production set up as follows; Django REST Framework backend Vuejs frontend Docker container that builds Vuejs for production and copies to Django Docker container /static/ and /template/ folders nginx reverse proxy to handle incoming requests Everything works fine when I navigate to home page (no backend API calls on homepage) and then navigate around the SPA using the navigation drawer. I start to get problems when I try to go directly to a Page in the SPA. The backend API requests fail, the response is HTML (I would have expected JSON) and it displays the message from my index.html (SPA page) that javascript is not enabled (the message withing the <noscript> tags). I have seen some people suggest this is related to Vue router being in history mode, which I would like to keep. The main suggested remedy is to add try_files $uri $uri/ /index.html; as a catch all to the nginx config. However, as I am simply proxying all requests to Django to handle the initial stage of routing, and I already have a catch all in my urls.py file (re_path(r"^.*/$", TemplateView.as_view(template_name="index.html"), name="frontend")) then I think I have this covered. Why would the API requests (which … -
Why django temlate if statement works wrong?
I am using Django 3.1.0 and i have problem with the below if statement. {% if group == "TEACHER" %} {% include "staticPages/components/teacher_dash.html" %} {% else %} {% include "staticPages/components/student_dash.html" %} {% endif %} the group variable stored the name of user.Groups.objects.first().name as string. While the group variable is equal to TEACHER it runs the forth line instead of the second line. I have tried printing out the group variable and copying it to the if condition but it did not worked. Every answer would be appreciated. -
how to use jinja2 in Django 3.1
Now I am using the Django 3.1 template engine but I am not satisfied with it. But I see that jinja2 template engine is very powerful that it. Thought Django says it has support for jinja2 template engine and I was following this Django documentation, but I couldn't use that. So, please tell me how do I do it? -
Subset of Django Group model in Form
I have a model for an event which contains the user and a group. curr_User = settings.AUTH_USER_MODEL class CoronaEvent(models.Model): #query_set = Group.objects.filter(user=curr_User) user = models.ForeignKey(curr_User, default=1, null=True, on_delete=models.SET_DEFAULT, related_name='group') group = models.ForeignKey(Group, on_delete=models.CASCADE) title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) slug = models.SlugField(unique=True) event_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Within my form (I use crispy forms) I want to only offer the list of groups, the current user is member of. After selecting a group I want to save the result. What I currently have achieved is to pass the group list from current user (request.user.groups.all() to my form and set the list (by using value_list()) as choices for the choisefield. But than Django is not able to save the results because the model expects an instance of group instead of the couple. How can I achieve two use a subset of group in my choices and save the selected group? -
I dont understand why my django signals isnt creating object into database
Im trying to build a notification app where a user follows another user, they get notified in a notification page, my problem now is that i don't understand why the signals isnt creating an object into the notification model database. Please help. Heres the code Models: class Notification(models.Model): assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notifications_assigned_to_user") group = models.CharField(max_length=2, choices=notification_types, default='N') creation_date = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) body = models.TextField(default='No Description') pk_relation = models.IntegerField(blank=True, null=True) def __str__(self): return f"For: {self.assigned_to.username} // id: {self.id}" Signals.py: @receiver(post_save, sender=Follow) def create_notification(*args, **kwargs): follow = kwargs['instance'] if kwargs['created']: # if task.created_by != task.assigned_to: if follow.follow_user != follow.user: Notification.objects.create( assigned_to = follow.user, group='NF', body=f"{follow.follow_user} followed you! ID: {follow.id}", pk_relation=follow.id ) else: # if follow.created_by != task.assigned_to: if follow.follow_user != follow.user: if follow.follow_user != follow.old_instance.follow_user: Notification.objects.create( assigned_to = follow.user, group='NF', body=f"{follow.follow_user} unfollowed you.", pk_relation=follow.id ) @receiver(post_save, sender=Notification) def send_notification_info(*args, **kwargs): if kwargs['created']: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( f"notification_group_{kwargs['instance'].assigned_to.id}", { 'type':'notification_info' } ) Please help. Im not too good, i feel i have left something out