Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
render_to_string seems to remove value of an variable
I am creating a like unlike button in Django and I ran into a wall. I am using ajax grab id and post to render to string. When button gets clicked first time everything is fine but render_to_string does not return value attr. And I have no idea why? def in views I have: def like_post(request): # post = get_object_or_404(Post, id=request.POST['post_id']) id = request.POST.get('id') post = get_object_or_404(Post, id=id) # check if this user already is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'is_liked': is_liked, 'value': id, } if request.is_ajax(): html = render_to_string('post/like_section.html', context, request=request) print("=====4======") print(context) print("=====4======") return JsonResponse({'form': html}) section where this is being rendered: <div id="like-section"> {% include 'post/like_section.html' %} </div> my jquery $(document).on('click', '#like', function(e) { e.preventDefault(); var id = $(this).attr("value"); var url = '{% url "like_post" %}'; $.ajax({ type: 'POST', url: url, data: { id: id, csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: 'json', success: function(response) { $('#like-section').html(response['form']) }, error: function(rs, e) { console.log(rs.responseText) } }); }); section that is being rendered <form action='{% url "like_post" %}' method="post"> {% csrf_token %} {% if is_liked %} <button name="post_id" class="likes" id="like" type="submit" value="{{ Post.id }}" like-count="{{ Post.likes.count }}">click 1</button> {% … -
Calling a JS function from iterated objects on pageload
Good evening, I want to set my progressbars dynamically through Javascript by replacing the width value to the calculated percentage. I am running Django with a Postgres DB. Now I can set the styling just fine through a JS function but how would I have the function trigger at pageload? Through the view I can pass the relevant number of votes for the iterated object (poll_product) and the total nr of votes. Those two I'd like to pass to my JS function as arguments, so I can calculate the percentage there and set it. I hope I explained it clearly enough, but please ask away for anything I need to elaborate on. {% for poll_product in poll_product_list %} <form action="{% url 'add_vote' poll_product.id %}" method="POST"> {% csrf_token %} <div class="row mt-1"> <div class="col-8"> <h5>{{ poll_product.product_type }} : {{ poll_product.votes }}</h5> </div> <div class="col-4"> {% if user.is_authenticated and not voted %} <input type="submit" class="btn-sm btn-dark" value="Vote"> {% endif%} </div> /* ------------ below is the relevant part ---------------- */ <div class="col-6 progress"> <div id="progressBar{{poll_product.id}}" class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> <input type="hidden" name="redirect_url" value="{{ request.path }}"> </form> {% endfor %} -
Select a valid choice. ... is not one of the available choices
Hello fellow Django enthusiasts, I am trying to create a simple Django 2.2 application with single model, single model form + custom field and a simple CreateView. I am populating the choices dynamically based on a http call to a outside url. The dropdown is populated fine, but when I try to submit my form I am getting an error: Select a valid choice. ... is not one of the available choices and the form is refreshed with new 3 suggestions in the dropdown. models.py class GhostUser(models.Model): first_name = models.CharField("User's first name", max_length=100, blank=False) last_name = models.CharField("User's last name", max_length=100, blank=False) ghost_name = models.CharField("User's ghost name", max_length=100, blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.ghost_name}" def get_absolute_url(self): return reverse('ghost_names:ghost-update', kwargs={'id': self.id}) views.py class GhostCreateView(CreateView): template_name = 'ghost_create.html' form_class = GhostUserForm success_url = '/' # def get_context_data(self, **kwargs): # data = super().get_context_data(**kwargs) # url = "https://donjon.bin.sh/name/rpc-name.fcgi?type=Halfling+Male&n=3" # resp = urllib.request.urlopen(url) # names = resp.read().decode('utf-8') # data['ghost_suggestions'] = names.splitlines() # return data forms.py class GhostUserForm(forms.ModelForm): ghost_name = forms.ChoiceField(choices=[], widget=forms.Select()) class Meta: model = GhostUser fields = ['first_name', 'last_name'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ghost_name'].choices = tuple(get_ghost_names()) def get_ghost_names(): url = "https://donjon.bin.sh/name/rpc-name.fcgi?type=Halfling+Male&n=10" resp = urllib.request.urlopen(url) data = resp.read().decode('utf-8').splitlines() names … -
Third party authentication for Django + React app
I am having an app with Django backend and React frontend and I'm using Azure AD for authentication. Basically, the frontend will try to authenticate users with Azure AD to obtain a token. Then, when users interact with the backend, the API call will include this token as well. At the backend, when received an API call, it will try to talk to Azure AD again to verify this token to make sure that this is a valid API request. Now, I'm thinking if there is a better way to do this, since for every API call, backend has to check for the validity of the token and it's kinda slow down the whole process. Is there anyway to improve the performance of this architecture? Thanks! -
Python Pillow - Facing issue with crop()
I am using jquery-cropper.js to crop an image on front end and then pass the values to Django form as shown below. def save(self): photo = super(MyModelForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.profile_pic) cropped_image = image.crop((int(x), int(y), int(w+x), int(h+y))) cropped_image.save(photo.profile_pic.path) #resized_image = cropped_image.resize((min(new_width, new_height), min(new_width, new_height)), Image.LANCZOS) #resized_image.save(photo.profile_pic.path) return photo The issue at the moment is that image is cropped fine on the front end but not on the backend. I get black area in the cropped pic. I want exact image as I see on the front end. The coordinates on the front end and backend are same. The cropped image is like -
Make migrations several files django
I have django project with the next structure: [projectname]/ ├── core/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── custom_user/ │ ├── ...#some files │ └── models/ │ ├── user.py │ └── tags.py │ └── manage.py How I can to run command makemigrations for several files (for user.py and for tags.py), now I'm trying to implement it by command ./manage.py makemigrations custom_user, but I'm getting the next info No changes detected in app 'custom_user'., I've defined the app in settings.py file in installed_apps as: INSTALLED_APPS = [ 'custom_user.apps.CustomUserConfig' ] and in apps.py file too as: class CustomUserConfig(AppConfig): name = 'custom_user' Nevertheless if I add my models to usual models.py file everything works.