Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test that anything in a django-accessed database has changed?
I'm refactoring some code and adding an atomic.transaction block. We have some code that performs auto-updates en-masse, after the atomic block. (It can't be in the atomic block, because it traverses some many-related tables, which requires queries since the ORM doesn't store the distinct relations.) According to my reading of the code, it seems impossible that any changes could occur, but having a test to prove it would be nice in case someone makes a bad code edit in the future. So how would I go about writing a test that proves nothing in the database has changed between the start of the test and the end of the test? The database is postgres. We currently have it configured for 2 databases (the database proper and a "validation" database which I'd created after we discovered the loading code had side-effects in dry-run mode. I'm in the middle of a refactor that has fixed the side-effects issue and I just added the atomic transaction block. So I would like to write a test like this: def test_no_side_effects_in_dry_run_mode(self): orig_db_state = self.get_db_state() # How do I write this? call_command( "load_animals_and_samples", animal_and_sample_table_filename=("data.xlsx"), dry_run=True, ) post_db_state = self.get_db_state() # How do I write this? self.assertNoDatabaseChange(orig_db_state, … -
Django ImproperlyConfigured
I'm fairly new to programming and I was learning Python by following the textbook No Starch Python. There is a chapter on Django and I followed the steps of the textbook. However, when I run the program: from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text I will get this error message: Traceback (most recent call last): File "/Users/admin/learning_log2/learning_logs/models.py", line 4, in class Topic(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/models/base.py", line 127, in new app_config = apps.get_containing_app_config(module) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/init.py", line 92, in getattr self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/init.py", line 72, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can anyone tell me why it is the case and what can I do? Thank you very much. P.S. I know there is already a post on this but I tried what was written without any results. Also, I'm on macOS High Sierra version 10.13.6 if this information is relevant. I tried whatever I … -
How can I get the meta data in Json format from a GitLab URL without using a personal token key and without project ID in Python (Django framework)?
I tried many codes: url = "https://gitlab.com/meta_tool/repository" parsed_url = urlparse(url) path_parts = parsed_url.path.split("/") owner = path_parts[1] repo_name = path_parts[2] gitlab = Gitlab('https://gitlab.com') project = gitlab.projects.get(owner+"/"+repo_name) print(project.name) Or other codes but some did not work. -
Serializing Dict Field inside List : ValueError: Cannot assign "OrderedDict
I am expanding JSON data from my last question and trying to save it to the database. Period model contains startDate and endDate because the JSON object could have all 3, or maybe one of them so I want to make them options. I am following steps given in the documentation for Writable nested representation but I am unable to get the same results Commented out code are the attempts I made to get the data to save. When I am trying to save the data, I get ValueError: Cannot assign "OrderedDict([('instant', '2020-09-26')])": "Cashcashequivalentsrestrictedcashandrestrictedcashequivalents.period" must be a "Period" instance. Models: class Basetable(models.Model): basetable = models.AutoField(primary_key=True) CompanyId = models.IntegerField() class Cashcashequivalentsrestrictedcashandrestrictedcashequivalents(models.Model): cashtable = models.AutoField( primary_key=True) unitRef = models.CharField(max_length=100) value = models.CharField(max_length=100) decimals = models.CharField(max_length=100) basetable_id = models.ForeignKey(Basetable, on_delete=models.CASCADE) class Period(models.Model): period = models.AutoField(primary_key=True) instant = models.CharField(blank=False, max_length=100, null=True) startDate = models.CharField(blank=False, max_length=255, null=True) endDate = models.CharField(blank=False, max_length=255, null=True) cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id = models.OneToOneField( Cashcashequivalentsrestrictedcashandrestrictedcashequivalents, on_delete=models.CASCADE) Serializer: class PeriodSerializer(serializers.ModelSerializer): # instant = serializers.DictField( # child=serializers.CharField(required=False, max_length=255)) # startDate = serializers.DictField( # child=serializers.CharField(required=False, max_length=255)) # endDate = serializers.DictField( # child=serializers.CharField(required=False, max_length=255)) instant = serializers.CharField(required=False, max_length=255) startDate = serializers.CharField(required=False, max_length=255) endDate = serializers.CharField(required=False, max_length=255) cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id = serializers.IntegerField( required=False) # serializer = DictField(child = charField) somethhing like … -
using EmailMultiAlternatives in Django but after sending email, then rendering problem
After sending html email by using EmailMultiAlternatives in Django, renderig problem occurred. I wanted to show the user email an email is being sent to your email {{ email }} But instead of displaying proper email address, it was displayed as follows "<django.core.mail.message.EmailMultiAlternatives object at 0x7f7b11bdffa0>" How can I fix this problem? views.py #html email configuration html_content = render_to_string("basecamp/html_email-inquiry.html", {'name': name, 'contact': contact, 'email': email, 'message': message,}) text_content = strip_tags(html_content) email = EmailMultiAlternatives( "Inquiry", text_content, '', [email] ) email.attach_alternative(html_content, "text/html") email.send() return render(request, 'basecamp/inquiry_details.html', {'name' : name, 'email': email, }) else: return render(request, 'basecamp/inquiry1.html', {}) inquiry_details.html <div class="py-md-6"> <h1 class="text-light pb-1">Thank you! {{ name }}</h1> <br> <p class="fs-lg text-light">An email is being sent to your email now</span></p> {{ name }} is displayed correct name but only email is not displayed proper email address. it is displayed like this; <django.core.mail.message.EmailMultiAlternatives object at 0x7f7b11bdffa0> -
NGINX Response Header missing Access-Control-Allow-Origin header when uWSGI - Djago application timesout
Our project is using the typical setup with a NGINX application gateway, uWSGI application container and a Django application. Django is configured using cors middleware and successfully handles requests from cross domains. However, one of our endpoints tars large files for download, which can take a significant amount of time. If it takes too long uWSGI times out and NGINX returns a response that lacks Access-Control-Allow-Origin header. We have increased uwsgi_connect_timeout and uwsgi_read_timeout values in the NGINX config to address most cases. Since, Django is handling cors and thus the Access-Control-Allow-Origin header, NGINX doesn't have those values to return to the client. Does anyone know what uWSGI or NGINX settings I need to get the correct headers? A simplified version of our nginx config: upstream results_uwsgi { server unix:///opt/app_manager/app_manager.sock; } server { listen 80; server_name \$hostname; return 301 https://\$host\$request_uri/; } server { listen 443 http2 ssl; listen [::]:443 http2 ssl; server_name \$hostname; charset utf-8; stub_status on; # adjust to taste client_max_body_size 75M; large_client_header_buffers 4 128k; location / { uwsgi_pass results_uwsgi; include uwsgi_params; } location /api { uwsgi_connect_timeout 10000s; uwsgi_read_timeout 10000s; sendfile on; uwsgi_pass results_uwsgi; include uwsgi_params; } } Our uWSGI configuration: [uwsgi] app_root = /opt/app_manager # emperor = /etc/uwsgi/vassals chdir … -
Is there an alternative to map() that doesn't return anything?
With the way that map() is designed it seems like it is intended to be used specifically when you are trying to return a list of modified things. I am wondering, is there an alternative to map() that is designed specifically for when you do not want to return whatever is being modified? I am currently working in a django project where I would like to set the initial value of a few fields if the instance already has data for these fields. Here is an example (note: I excluded some code not relevant to the discussion to keep it cleaner): class EquipmentStatusForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_field(["fk_user"]) def init_field(self, attr): if hasattr(self.instance, attr): if getattr(self.instance, attr) != "" and getattr(self.instance, attr) is not None: self.initial[attr] = getattr(self.instance, attr) Say I wanted to extend this to use a list of attrs rather than a single one, and then set the initial value of all of these. I don't need the results to be returned because I am not actively doing anything with these attrs after I modify them. Is there a built in alternative to map() designed for this? Or am I really just stuck using a for … -
How to print object's values with "annotate()" and "for loop" in ascending order?
I have Category and Product models below. *I use Django 3.2.16: # "models.py" from django.db import models class Category(models.Model): name = models.CharField(max_length=20) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=50) Then, when running test view to print id, name and product__count with annotate() and index as shown below: # "views.py" from .models import Category from django.http import HttpResponse from django.db.models import Count def test(request): qs = Category.objects.annotate(Count('product')) print(qs[0].id, qs[0].name, qs[0].product__count) print(qs[1].id, qs[1].name, qs[1].product__count) print(qs[2].id, qs[2].name, qs[2].product__count) print(qs[3].id, qs[3].name, qs[3].product__count) return HttpResponse("Test") These are printed in ascending order properly as shown below: 1 Fruits 14 2 Vegetables 10 3 Meat 4 4 Fish 3 But, when running test view to print id, name and product__count with annotate() and for loop as shown below: # "views.py" # ... def test(request): qs = Category.objects.annotate(Count('product')) for obj in qs: print(obj.id, obj.name, obj.product__count) return HttpResponse("Test") These are printed in descending order improperly as shown below: 4 Fish 3 2 Vegetables 10 3 Meat 4 1 Fruits 14 [25/Jan/202 In addition, when running test view to print id and name with all() and index as shown below: # "views.py" # ... def test(request): qs = Category.objects.all() print(qs[0].id, qs[0].name) print(qs[1].id, qs[1].name) print(qs[2].id, qs[2].name) print(qs[3].id, qs[3].name) return … -
How to use variables in django models.py, (DEFAULT properties of fields)
I would like that, when clicking on one of the companies below, a variable is stored (until the browser is closed) with the company's code. And, I need this variable to populate the 'CompanyCode' fields as default value. FOR EXAMPLE: class Employee(models.Model): class Meta: db_table = 'employee' CompanyCode= models.IntegerField( null=False, blank=None, default = 'VARIABLE', db_column='CompanyCode' ) After being stored in the database, I need to make a query to show all tuples where CompanyCode is equal to a certain value. Could someone tell me a python, django component that I could use to separate the data for each company? I thought of using JavaScript Local Storage at first. -
How to assign HTML Form fields to DJANGO Model Forms without using ModelForm
I am trying to make pretty looking HTML form where each fields are formatted with some validation and icons. Once these fields are submitted I want to save to Model instance using either using Model form or some other approach which allows to make this operation smooth. Here is my code snippet: model.py: class Client(Model): client_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) date_of_birth = models.DateField(blank=True, null=True) email = models.EmailField(null=True) form.py: class ClientNewForm(forms.ModelForm): class Meta: model = Client fields = "__all__" view.py (I know this is wrong but need help to figure out what's the best way to do this): class ClientCreateView(CreateView): model=Client form_class = ClientNewForm template_name = 'Client/client_new.html' context_object_name = 'client' # refer the object as patient in template success_url = reverse_lazy('WebApp:clients') def form_valid(self, form): model = form.save(commit=False) #model.submitted_by = self.request.user model.save() messages.success(self.request, "The Client is created successfully.") return super(ClientCreateView, self).form_valid(form) Template: <div class='row'> <div class="col-md-8 col-sm-8 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>NEW REGISTRATION</h2> </div> <div class="x_content"> <form class="form-horizontal form-label-left input_mask" action="" method="post"> {% csrf_token %} <div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback"> <input type="text" class="form-control has-feedback-left" id="in-fn" placeholder="First Name" name="first_name"> <span class="fa fa-user form-control-feedback left" aria-hidden="true"></span> </div> <div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback"> <input type="text" class="form-control … -
Where is it better to start creating a simple social network(Django)?
I want to create my own simple social network (where you can post posts, videos, photos, etc.), but I don't know where to start. I'm already learning Python (Django), but I don't know this language (framework) professionally. Can you advise which videos, articles, forums, tutorials (and more) will help to create this simple project? -
django.urls.exceptions.NoReverseMatch: Reverse for 'index' with arguments '(5,)' not found. 1 pattern(s) tried: ['index/\\Z']
Django problem views.py def likes_up(request,post_id): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.like.filter(id=request.user.id).exists(): post.like.remove(request.user) else: post.like.add(request.user) return HttpResponseRedirect(reverse('index', args=[post_id]))` models.py class Post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.CharField(max_length=500,null=True,blank=True) timestamp = models.DateField(auto_now_add=True) like = models.ManyToManyField(User,blank=True,related_name="liked_user") def number_of_likes(self): return self.like.count()` index.html {% if user.is_authenticated %} <form action="{% url 'like-post' pst.id%}" method="POST"> {% csrf_token %} {% if post_is_liked %} <button type="submit" name="post_id" value="{{pst.id}}" class="btn btn-info">Unlike</button> {% else %} <button type="submit" name="post_id" value="{{pst.id}}" class="btn btn-info">Like</button> {% endif %} </form> {% endif %} <strong class="text-secondary">{{ number_of_likes }} Like{{ number_of_likes|pluralize }}</strong>` I try to make post like and unlike button and ı want to show page that how many users liked post? But I got this error: How can I solve this problem? Internal Server Error: /like/5 Traceback (most recent call last): File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\OSMAN MERT\Desktop\env\blogs\mysite\blog\views.py", line 102, in likes_up return HttpResponseRedirect(reverse('index', args=[post_id])) File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'index' with arguments '(5,)' not found. 1 pattern(s) tried: ['index/\Z'] -
override get_queryset DetailView
I'm new in Django and i try to use Class Based Views for my project, but i have problem in this. I wanna login a user into a page with its primary key but i don't know how to override query_set. here is my code, any help will grateful. in the views.py : def UserPage(LoginRequiredMixin, DetailView): template_name = 'user_page.html' model = User login_url = '/login/' def get_queryset(self): pass in urls.py: path('user/<int:pk>/' , UserPage.as_view()), I write this : return User.objects.get(pk=pk) but i got this error : Type Error missing 1 required positional argument: 'pk' -
Assign each value using different loops in python
Hi I got a loop where I get different parameters (age, date, role, etc.), and I got an array where I get these values. How can I assign each value to eache parameter. I'll add some code below I tried this but obviosly didn't work parameters = Parametros.objects.filter(job_id=job.id) if request.method == 'POST': for parameter in parameters: #Update parameters params = request.POST.getlist('parameter') for i in range(len(params)): cursor.execute("UPDATE Jobs_parametros SET parameter_value='" + params[i] + "' WHERE parameter_name='" + parameter.parameter_name + "' AND job_id=" + str(job.id)) Here we can see parameters where I'm assigning parameter.parameter.name for the differente names. After that we can see the array where I get the values called "params". I want to assign each value I get form params to the name of the parameter to execute the code showed in the last line The result that I got with the code showed is each parameter name with the last value I added. The values are updated but only take the last value in my form and didn't assigned my values like the date and age for eache parameter name -
django foreign key filtering in admin panel
class City(models.Model): name = models.CharField(max_length=200, null=True, blank=False) class District(models.Model): city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=False) class ShippingAddress(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, null=False) district = models.ForeignKey(District, on_delete=models.CASCADE, null=False) I would like to filter the admin panel by city (selected city). in order to filter too much similar districts names. If someone has another way to do it no problem, that was a junior try, waiting for your advice. -
How can I run Django on a subpath on Google Cloud Run with load balancer?
I'll preface by noting that I have a system set up using Google Cloud Run + Load Balancer + IAP to run a number of apps on https://example.com/app1, https://example.com/app2, etc, and up to now I've only deployed Streamlit apps this way. The load balancer is directing traffic to each app in Cloud Run according to subpath (/app1, ...), and I used the --server.baseUrlPath=app2 option of streamlit run with no problems. Now I'm trying to get a 'hello, world' Django 4.1.5 app running on https://example.com/directory, and I can't seem to get the routes right trying differing suggestions here, here, and here. The Dockerfile ends with CMD exec poetry run gunicorn --bind 0.0.0.0:${PORT} --workers 1 --threads 8 --timeout 0 example_dir.wsgi:application First, the canonical solution. I added FORCE_SCRIPT_NAME = "/directory" in settings.py. Here's example_dir/urls.py: urlpatterns = urlpatterns = [ path("admin/", admin.site.urls), path("", include("directory.urls")), ] and here's directory/urls.py: urlpatterns = [ path("", views.hello, name="hello"), ] Visiting https://example.com/directory returns Page not found (404) Request Method: GET Request URL: http://example.com/directory/directory Using the URLconf defined in example_dir.urls, Django tried these URL patterns, in this order: 1. admin/ 2. [name='hello'] That Request URL is surprising and weird. Adding either USE_X_FORWARDED_HOST = True or SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') or … -
Overlapping two ImageField in a Django form
I’m trying to edit a user’s profile in django but when editing the banner image and the profile pictura overlap. I mean, I put a different image on each one, but when I save the form, I get the same image. When a profile is created both are set by default as it comes in models.py. views.py @login_required def EditProfile(request): user = request.user.id profile = Profile.objects.get(user__id=user) user_basic_info = User.objects.get(id=user) if request.method == 'POST': form = EditProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): user_basic_info.first_name = form.cleaned_data.get('first_name') user_basic_info.last_name = form.cleaned_data.get('last_name') profile.picture = form.cleaned_data.get('picture') profile.banner = form.cleaned_data.get('banner') profile.location = form.cleaned_data.get('location') profile.url = form.cleaned_data.get('url') profile.birthday = form.cleaned_data.get('birthday') profile.bio = form.cleaned_data.get('bio') profile.save() user_basic_info.save() return redirect('users:profile', username=request.user.username) else: form = EditProfileForm(instance=profile) context = { 'form':form, } return render(request, 'users/edit.html', context) forms.py class EditProfileForm(forms.ModelForm): first_name=forms.CharField( widget=forms.TextInput(attrs={ 'class': 'shadow-sm focus:ring-indigo-500 dark:bg-dark-third dark:text-dark-txt focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md', }) ) last_name=forms.CharField( widget=forms.TextInput(attrs={ 'class': 'shadow-sm focus:ring-indigo-500 dark:bg-dark-third dark:text-dark-txt focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md', }) ) picture = forms.ImageField(label='Profile Picture', required=False, widget=forms.FileInput) banner = forms.ImageField(label='Banner Picture', required=False, widget=forms.FileInput) location = forms.CharField(widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), max_length=25, required=False) url = forms.URLField(label='Website URL', widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs … -
why section of my django project views getting queryset error?
Hello I have a django project for calorie tracker and when I go to fooditem_create url I get this error : FoodItemCreateView is missing a QuerySet. Define FoodItemCreateView.model, FoodItemCreateView.queryset, or override FoodItemCreateView.get_queryset(). this is my views: from .forms import * from django.urls import reverse_lazy from .models import * from accounts.models import CustomUser from django.views import generic from django.views.generic import ListView from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin class FoodItemCreateView(LoginRequiredMixin, generic.CreateView): mode = Fooditem template_name = 'fooditem_create.html' fields = "__all__" success_url = reverse_lazy('fooditem_list.html') class FoodItemListView(LoginRequiredMixin,ListView): model = Fooditem template_name = 'fooditem_list.html' fields = "__all__" class FoodItemDeleteView(LoginRequiredMixin,generic.DeleteView): model = Fooditem template_name = 'fooditem_delete.html' success_url = reverse_lazy('fooditem_list.html') @login_required(login_url='login') def SelectFoodCreateView(request): usernow = CustomUser.objects.get(id=request.user.id) form = selectfoodForm(request.user, instance=usernow) if request.method == "POST": form = selectfoodForm(request.user, request.POST, instance=usernow) if form.is_valid(): name = form.cleaned_data.get('name') category = form.cleaned_data.get('category') quantity = form.cleaned_data.get('quantity') person = form.cleaned_data.get('person') selectedfood = Selectfooditem.objects.create( name=name, quantity=quantity, category=category, person=person) selectedfood.save() return redirect('/manage/profile') else: form = selectfoodForm(request.user) context = {'form': form} return render(request, 'addfood_create.html', context) @login_required(login_url='login') def ProfileView(request): usernow = CustomUser.objects.get(id=request.user.id) calorielimit = usernow.calorielimit selectedfood = Selectfooditem.objects.filter(person=request.user) calorieconsumed = 0 calorieleft = calorielimit for food in selectedfood : calorieconsumed+= (food.name.calorie * food.quantity) calorieleft = calorielimit - calorieconsumed context = { … -
404 error when requesting a file that exists
I'm trying to deploy a Django project using a VPS - it uses Apache and mod_wsgi. (It works fine locally). My homepage is displayed, but no static file is found, leading to a goofy display. I have configured my static files this way : settings.py : STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' call in template : ` ` After that I ran collectstatic, which created a "static" folder on root, as expected. I have checked via SSH and FTP, it is there (see screenshot 1 : ), with the correct permissions. The URL to access it should then be : /static. But I get this 404 error, even though my explorer seems to look for the correct adress (see screenshot 2 : ) I have only basic academic knowledge on this topic, but I simply don't understand how can I get a 404 when requesting a file that seems to exist. I will take any suggestion, since I've tried everything I could think of. Thank you very much ! Also, I added this in urls.py : urlpatterns = [ path('', home, name='home'), path('output/<str:region>/<str:summoner_name>', output, name='output') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I didn't think this was necessary, but tried anyway. It … -
how to make django admin theme dark?
can I somehow set a dark theme in django admin and make it look like in the screenshot below -
Assign each value in a loop in python
Hi I got a loop where I get differente parameters (age, date, role, etc.), and I got an array where I get these values. How can I assign each value to eache parameter. I'll add some code below I tried this but obviosly didn't work parameters = Parametros.objects.filter(job_id=job.id) if request.method == 'POST': for parameter in parameters: #Update parameters params = request.POST.getlist('parameter') for i in range(len(params)): cursor.execute("UPDATE Jobs_parametros SET parameter_value='" + params[i] + "' WHERE parameter_name='" + parameter.parameter_name + "' AND job_id=" + str(job.id)) -
Gunicorn Config File I've Created Doesn't Exist
I am using Django and Gunicorn to create a blog and am wanting to run my config file that I have created. This is the path to my config file (the conf folder is at the same level as manage.py): /var/www/website.co.uk/blog/DjangoBlog/Articles/conf/gunicorn_config.py I am in this path: /var/www/website.co.uk/blog/DjangoBlog/Articles and run this command: gunicorn -c gunicorn_config.py Articles.wsgi However, it returns the error: Error: 'gunicorn_config.py' doesn't exist Is Gunicorn looking in the wrong place for my config file? Any help would be massively appreciated. I have not been able to solve this for a while. Kind regards -
Vue.js are not displaying images from Django media folder
So, i have up and running Django server on localhost. There's is a Vue page, whick is authorized and able to fetch models data. If i inspect page, i see that img element have correctly resolved URL, and image exsists and can be loaded. But I got this: As you can see, other model parameters (such as name and price) can be loaded. Here's how I loading img. <figure class="image mb-4"> <img v-bind:src="product.get_thumbnail" /> </figure> I've checked media folder paths, and believe they are correct MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' Also, if I am able to load image by the link gotten via page inspection, why can't it be loaded on page itself? -
How to run long running task behind the scence in django class based view?
I want to run long running task in Django class based Redirectview. Before this running task to complete I want to return template. Here is my code. I try with this code. class Redirect_to_page(RedirectView): async def sleep_long(self): for i in range(1,10): print(f'Run {i}') await asyncio.sleep(1) pass query_string = True pattern_name = 'pages:redirect_page' def get_redirect_url(self, *args, **kwargs): asyncio.run(self.sleep_long()) print('This run before complete!') return super().get_redirect_url(*args, **kwargs) and this is result. Run 1 Run 2 Run 3 Run 4 Run 5 Run 6 Run 7 Run 8 Run 9 This run before complete! But I want result like_ Run 1 This run before complete! Run 2 Run 3 Run 4 Run 5 Run 6 Run 7 Run 8 Run 9 -
Django channels daphne: missing 1 required positional argument: 'send'
Hi I am having issues getting django channels working in production. I am running gunicorn --bind 0.0.0.0:8000 project_name.asgi to test that my ASGI setup is working correctly (This all works on my local machine which is super odd. Maybe I am missing something): This is the error I keep getting :( I have tried everything online but nothing is working: Traceback (most recent call last): File "/home/quilt/quilt_env/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 136, in handle self.handle_request(listener, req, client, addr) File "/home/quilt/quilt_env/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 179, in handle_request respiter = self.wsgi(environ, resp.start_response) TypeError: ProtocolTypeRouter.__call__() missing 1 required positional argument: 'send' my requirement file has the following: channels==4.0.0 channels-redis==4.0.0 daphne==4.0.0 Django==4.1.5 billiard==4.1.0 asgiref==3.6.0 This is my settings file: ASGI_APPLICATION = 'project_name.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ["127.0.0.1", "6379")], }, }, } This is my asgi.py setup: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') django.setup() from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack import notifications.routing application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( JWTAuthMiddlewareStack( URLRouter( notifications.routing.websocket_urlpatterns ), ) ) }) This is my routing in notification app: from django.urls import path from notifications import consumers websocket_urlpatterns = [ path("ws/", consumers.NotificationConsumer.as_asgi()), ] And then this is my consumer.py file: import json from asgiref.sync import sync_to_async from …