Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Possible reason for django template not loading upadted static file
<section> website content here </section> {% load static %} <script src="{% static 'notifications.js' %}" type="text/javascript"></script> <script src="{% static 'presentation.js' %}" type="text/javascript"></script> That code worked as it should ie. loading current versions of .js files. After some time I noticed a typo in notifications.js file. After fixing the typo and saving the file local development server is still loading version without fix. I tried clearing browser cache and history as well as rebooting device and problem still occurs. Any possible fix? -
What is the right way to set up Gunicorn on my Django app?
everyone! Could you please help me with setting up Gunicorn for Django application. I'm going through clear and great digital ocean tutorial and don't know how to access my wsgi.py file for Gunicorn. In example it is shown like this: cd ~/myprojectdir gunicorn --bind 0.0.0.0:8000 myproject.wsgi But my wsgi.py file has another address: ~/myprojectdir/LibrarySite/locallibrary/wsgi.py. So, I did this way: cd ~/myprojectdir/LibrarySite/locallibrary gunicorn --bind 0.0.0.0:8000 locallibrary.wsgi And I get an error: No module named 'locallibrary' I'm sorry for such a dummy question, but what is the correct way to set file address right?Server error -
Django image saving
I wonder what is the best practices in saving images into ImageField in Django? class Image(models.Model): image = ... def save(self, *args, **kwargs): ... # resizing and saving the image super().save(*args, **kwargs) I want to save images but not in original size. I want to save only the resized image. As far as I know the super save method here additionally saves the original image to database. But I want it to save only resized to prevent data overflow. How to do that? -
trying to get wrong parameter on purpose in django unit testing
as part of project management course me and my partners creating a website to simulate buying and selling stock, and we're using yahoo finance API to get the Stocks and their details, and we're developing it in Django In the unit testing I'm sending on purpose a wrong stock name in the search system so I could check if its really showing a message 'Wrong Stock name', I'm doing it with sending a POST request with wrong stock name and the result is that the the specific unit test fails how could I check it? the unit test code: def test_Customer_wrong_stock(self): response = self.client.post(reverse('AgentSignUp:Search_Stock_cust'), data={ 'searchStock':'badStock'}) self.assertEqual(response.status_code,200) and the view function for the search: def SearchStock(response): if response.method == "POST": try: stockTicker = response.POST.get('searchStock') stock = yf.Ticker(stockTicker) stockData = stock.history(period="4y") stockData['Close'].plot(title=f"{stockTicker} stock price (in USD)") graph = plt.gcf() buf = io.BytesIO() graph.savefig(buf,format='png') buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) graph = stockData['Close'] price = stock.info['regularMarketPrice'] symbol = stock.info['symbol'] recom = stock.info['recommendationKey'] website = stock.info['website'] return render(response, "stock_view.html", {"price": price, "ticker": symbol, "recom": recom, "website": website, "graph": uri}) except: messages.error(response, f"Stock named {stockTicker} doesn't found or not exists") if response.user.is_Customer: return redirect('/customer_homepage') elif response.user.is_Agent: return redirect('/agent_homepage.html') elif response.user.is_Admin: return redirect('/admin_homepage.html') else: … -
How to copy data from fixtures to tenant schema table in Django-tenants?
Info: I am using django-tenants. I want to copy data from fixtures file to tenant schema table while creating new tenant. django-celery is handling the task. I want to run fixtures_data_load function after new tenant has been created I don't understand how can i do that! app.task() def fixtures_data_load(self): with open('fixtures/groups.json', encoding='utf-8') as data_file: # Convert json string to python object data = json.loads(data_file.read()) # Create model instances for each item for item in data: # create model instances... item = YourModel(*item) YourModel.objects.bulk_create(items) fixtures.json [ { "model": "auth.group", "pk": 1, "fields": { "name": "admin", "permissions": [] } }, { "model": "auth.group", "pk": 2, "fields": { "name": "producer", "permissions": [] } }, { "model": "auth.group", "pk": 3, "fields": { "name": "copy editor", "permissions": [] } }, { "model": "auth.group", "pk": 4, "fields": { "name": "reporter", "permissions": [] } }, { "model": "auth.group", "pk": 5, "fields": { "name": "anchor", "permissions": [] } }, { "model": "auth.group", "pk": 6, "fields": { "name": "nle", "permissions": [] } }, { "model": "auth.group", "pk": 7, "fields": { "name": "ticker oprator", "permissions": [] } }, { "model": "auth.group", "pk": 8, "fields": { "name": "assignment editor", "permissions": [] } } ] -
Sync on-premises folder with website's static folder in AWS
I have a Django web app deployed with AWS elastic beanstalk. It’s basically a website. The site reads data from a postgres db, combines it with some images located inside a static folder, and gives an outcome according to my needs. It works fine manually but my intention from the beginning was to make it renew its content automatically. Thus, I need to do two things: To upload the data from a csv file periodically (I’m doing it currently through an input form). And more importantly, to sync my on-premises windows server folder where the images are stored, with the above-mentioned static folder. I’m new to Django and web development in general, and my knowledge over cloud services is still limited, so I would appreciate a small guidance. My primary question is if such a thing exists and if it’s something common or at least possible, and secondly how to approach this and where to focus, in order not to waste time. Thanks in advance! -
Server side Processing Django datatables rest framework Query set filtering
I have a website which firstly designed to show dynamically added or removed models in datatables. Now the data increases and i added serverside processing. The issue is I have a custom page for each foreign key to show data that belongs to itself now i am stuck with how to filter queryset for the foreign key id and set an api url for server side processing. I hope i was clear. Thanks for your attention -
Django objects in array shows as its id's
I have an UserProfile, which have OneToOneField User. In UserProfile I have ManyToManyField Orders. When I get the orders from user.profile, it returns the array of it ID's, not the entire objects. UserProfile: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE, unique=False) orders = models.ManyToManyField(Order, blank=True) def __str__(self): return self.user.username Order: class Order(models.Model): car_brand = models.CharField(max_length=30) car_model = models.CharField(max_length=30) repair_type = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) Serializers: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ['car_brand', 'car_model', 'repair_type', 'user'] class UserProfileSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): orders = OrderSerializer(many=True) class Meta: model = UserProfile fields = ['user', 'orders'] And, the main part, if I making a GET request with Postman, I get this: { "user": 5, "orders": [ { "car_brand": "Ford", "car_model": "Galaxy", "repair_type": "Gearbox", "user": 5 } ] } And yeah, that's exactly what I want. But React GET returns another: 11 in this case, it is a ID of order, which described above. So, the main question: How to save this order not as ID, or read it not as ID. -
Get Queryset with more than one parameters
I have a models below, and in my ListView I want to get a queryset that returns according to the tatuador, total (lista_servico) and total (valor_servico). class servico(models.Model): choices_services = [('1', 'Tatuagem'), ('2', 'Corte de Cabelo')] tatuador = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Funcionário') cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE) lista_servico = models.CharField(max_length=1, choices=choices_services, blank=False, null=False, verbose_name='Lista de serviços') valor_servico = models.DecimalField(default='', max_digits=7, decimal_places=2, verbose_name='Valor do serviço') data_servico = models.DateTimeField(null=False, verbose_name='Data do serviço') marcar_servico = models.BooleanField(default=True) modo_pagamento = models.BooleanField(default=False, verbose_name='Cartão de crédito') -
Django Rest Framework Serializer to filter specific child to be nested under parent
There is a 4 levels nested relation. Country->State->District->road (that has all states in a country , all districts in a state and so on) A user sends data in separated arrays like country:["A","B"] state:["C","F","D"] and same for district and road. I want to have a json structure where only the user sent states are there and same for the other two levels also. Ex - [ { "country":[{ "name":"A", "states":[{ "name":"C", "district":[{ "name":"D"//only the user sent districts "road":[{"name":"saf"}] }] }] },{ "name":"B", .... }] }] How can i achieve this using serializers because serializers are giving me all the states irrespective of what user selected -
Locate the location of bus and student to their parent
I am working on a project in which location of bus and student will be shown to the parent. how can I render location of 2 different users to another user ( all are of different model class). Model classes are: class driver_detail(models.Model): d_user = models.OneToOneField(User, on_delete=models.CASCADE) driver_name = models.CharField(max_length=50) root_no = models.IntegerField() d_location = models.CharField(max_length=50,null=True) def __str__(self): return self.d_user.username class students(models.Model): suser = models.OneToOneField(User, on_delete=models.CASCADE,null=True) roll_no = models.CharField(max_length=10,primary_key=True,default=1) name = models.CharField(max_length=50) root_no = models.ForeignKey(driver_detail, on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now_add=True) locations = models.CharField(max_length=200,null=True) def __str__(self): return self.suser.username class parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) roll_no = models.ForeignKey(students, on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username -
Access many to many field from queryset Django
I have two models: class Vineyard(models.Model): name = models.CharField(max_length=255, blank=True) def __str__(self): return self.name class WineRegion(models.Model): name = models.CharField(max_length=255) vineyards = models.ManyToManyField(Vineyard, blank=True) def __str__(self): return self.name And I want to access all vineyards from the wine region. Here is what I've tried: if len(id_list) > 0: wr = WineRegion.objects.filter(id__in=id_list) vineyardList = wr.vineyards.all() But it gives me an error ---> AttributeError: 'QuerySet' object has no attribute 'vineyards' How can I solve this? -
Getting ['WSGIRequest' object has no attribute 'data'] error in DRF login api
Hi I am creating a login api in django restframework, but i got error wile test api in postman getting error WSGIRequest' object has no attribute 'data, i have trying mutiple way can't solve this error models.py class GmsUser(GmsBaseModel): first_name=models.CharField(max_length=255,null=True, blank=True) middle_name=models.CharField(max_length=255,null=True, blank=True) last_name=models.CharField(max_length=255,null=True, blank=True) user_name=models.CharField(max_length=255,null=True, blank=True, unique=True) password=models.CharField(max_length=255,null=True, blank=True) views.py @csrf_exempt @permission_classes((AllowAny,)) def gms_user_login(request): if request.method == 'POST': user=authenticate( request, user_name=request.data['user_name'], password=request.data['password'] ) users=GmsUser.objects.filter(id=request.data['user_name']).values_list('id',flat=True) query=GmsUserRole.objects.filter(user=users[0]).exists() if user is None: return JsonResponse({'error':'unable to login'}, status=400) else: try: if query: token = Token.objects.get(user=user) return JsonResponse({'token': token.key}, status=201) else: return JsonResponse({'error':'User does not have role'}, status=400) except Token.DoesNotExist: token = Token.objects.create(user=user) return JsonResponse({'token': str(token)}, status=200) -
Could not parse the remainder: 'slug=blog.slug' from ''blog_details'slug=blog.slug'
i am using slug field in my blogs. here's how i am creating slugs views.py def Creating_blog(request): form=BlogForm() if User.is_authenticated: if request.method=='POST': form=BlogForm(request.POST,request.FILES) if form.is_valid: blog_obj=form.save(commit=False) blog_obj.author=request.user title=blog_obj.blog_title blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4()) blog_obj.save() return redirect('index') return render(request,'blogs/creatingblog.html',context={'form':form}) Using slug to lead to the blog details page <a href="{% url 'blog_details' slug=blog.slug %}">Read More</a> but whenever i click on that it shows me raise TemplateSyntaxError("Could not parse the remainder: '%s' " django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: 'slug=blog.slug' from ''blog_details'slug=blog.slug' i have tried with slugify too <a href="{% url 'blog_details' slug=blog.slug|slugify %}">Read More</a> but it remains the same help me out please. -
Django how to display a tabular inline for model with two foreign keys on the same model?
I have a fight model with two ForeignKeys for Person on it: Fight person_a = models.ForeignKey("Person", related_name = 'person_a') person_b = models.ForeignKey("Person", related_name = 'person_b') When I display the admin for either Person, I want the Fight object to show up as a Tabular Inline for either Person, however I get the error "You must specify a fk_name attribute." But that only allows me to attach either person_a or person_b as the foreign key, and then in my Admin view for person, I only see one person reference within the Fight Inline. What's the syntax to get both to display? class FightAdminInline(admin.TabularInline): model=Fight fk_name = person_a # <—It only shows person_a in the tabular inline class PersonAdmin(admin.ModelAdmin): model=Person inlines=(FightAdminInline) -
Open pygame window from web page with django python
I'm trying to have a website where you can play games. You will eventually be able to click a button and launch a pygame window to play the game. To test whether I can do this with Django, I'm trying to launch the pygame window when I go to the home page as a proof of concept. However, I'm having trouble figuring out how exactly to launch the window. Here is my first attempt in views.py: from .games import game def home_page(request): title = "Home Page" template_name = "home.html" if request.user.is_authenticated: message = f'Hello there, {request.user}!' else: message = 'Hello there!' game.main() return render(request, template_name, {'title': title, 'message': message}) My game.py (located in a games folder, which is in the same directory as my views.py: import pygame import sys def main(): pygame.init() screen = pygame.display.set_mode((50, 50)) pygame.display.set_caption("Test") while True: screen.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() When I run the server and try to go 127.0.0.1:8000 (where my site is located), neither the page nor the pygame window would load. When I quit the server, the web page showed that it could not find the site. I think this was because the code … -
Django OSError due to path
I have been beating my head over this. In settings.py my template folder is declared like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['myproject\myproject\template'], This produces and OSError Exception Value: [Errno 22] Invalid argument: 'C:\\Users\\name\\Desktop\\django\\myproject\\myproject\\myproject\template\\home-view.html' However if I give the explicit path, this does not seem to be an issue and the page loads. Also the error has 3 times myproject but it should be 2, so the path should be this: 'C:\\Users\\name\\Desktop\\django\\myproject\\myproject\template\\home-view.html' and not this : 'C:\\Users\\name\\Desktop\\django\\myproject\\myproject\\myproject\template\\home-view.html' Could you please advise why is it doing that? Why is there an additional myproject folder showing up? -
Flutter notification with django channels
Please explain me how can i implement flutter notification with django channel socket . I am not getting any idea to connect flutter to the django socket channel for notification . -
How to calculate the time a user spends on a website?
Can you tell me how django can be used to track the time a user spent on a page in milliseconds, for example? -
try to update a my Cart with django, but i don't know whats im implementing wrong here
Django version = 4.0.4 Python == 3.9.12 os = osx here is my cart template, where I use a template tag to get access to my Order instance data for render it <div class="block-cart action"> <a class="icon-link" href="{% url 'core:cart' %}"> <i class="flaticon-shopping-bag"></i> <span class="count">{{ request.user|cart_item_count }}</span> <span class="text"> <span class="sub">Carrito:</span> Gs.{{ request.user|cart_total_count }} </span> </a> <div class="cart"> <div class="cart__mini"> <ul> <li> <div class="cart__title"> <h4>Carrito</h4> <span>( {{ request.user|cart_item_count }} Item en el carrito)</span> </div> </li> {% if request.user|cart_total_items != 0 %} {% for order_item in request.user|cart_total_items %} <li> <div class="cart__item d-flex justify-content-between align-items-center"> <div class="cart__inner d-flex"> <div class="cart__thumb"> <a href="product-details.html"> <img src="{{ order_item.item.image.url }}" alt=""> </a> </div> <div class="cart__details"> <h6><a href="product-details.html">{{ order_item.item.title }}</a></h6> <div class="cart__price"> <span>Gs. {% if order_item.item.discount_price|stringformat:".0f" %} {{ order_item.item.discount_price|stringformat:".0f" }} {% else %} {{ order_item.item.price|stringformat:".0f" }} {% endif %} x {{order_item.quantity}}</span> </div> </div> </div> <div class="cart__del"> <a href="{% url 'core:remove-from-cart-from-home' order_item.item.id%}"><i class="fal fa-times"></i></a> </div> </div> </li> {% endfor %} {%else%} {% endif %} <li> <div class="cart__sub d-flex justify-content-between align-items-center"> <h6>Subtotal</h6> <span class="cart__sub-total">Gs.{{ request.user|cart_total_count }}</span> </div> </li> <li> <a href={% url 'core:cart' %} class="wc-cart mb-10">Ver Carrito</a> <a href={% url 'core:checkout' %} class="wc-checkout">Finalizar Compra</a> </li> </ul </div> </div> here is the custom template tag @register.filter def cart_item_count(user): if user.is_authenticated: … -
How to have an object's pk as an integer?
I have this model: class Class(models.Model): class_id = models.IntegerField(blank=False) def save(self, *args, **kwargs): self.class_id = self.pk+1000 super(Class, self).save(*args, **kwargs) As you can see, I want pk to be added to 1000 and use that as class_id value. But I get this error: TypeError at /new-class unsupported operand type(s) for +: 'NoneType' and 'int' How can I have the pk as an integer? -
Django Admin: How to check TabularInline model field value
I want to check the value filled by user in Django Admin for TabularInline model. Maybe above sentence does not makes sense, if yes, please ignore above sentence, and below is more explanation to my requirement. My model has 2 classes (Filter and FilterCondA) as below: Filter has name of filter and id. class Filter(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) filter_name = models.CharField(max_length=32, unique=True, verbose_name=_("Name")) And FilterCondA has class FilterCondA(models.Model): DEVICE_FIELD = ((A, 'A'), (B, 'B'), (C, 'C'), (D, 'D')) opt_contains, opt_exact, opt_startswith, opt_endswith = 'contains', 'exact', 'startswith', 'endswith' OPERATORS = ((opt_contains, 'Contains'), (opt_exact, 'Exact'), (opt_startswith, 'Startswith'), (opt_endswith, 'Endswith')) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) fconda_filter = models.ForeignKey(Filter, null=True, blank=True, verbose_name=_('Filter')) fconda_field = models.CharField(max_length=512, choices=DEVICE_FIELD, blank=False, verbose_name=_("Device Field")) fconda_logic_op = models.CharField(max_length=16, choices=OPERATORS, blank=False, verbose_name=_("Operator")) fconda_value = models.CharField(max_length=64, null=True, blank=False, verbose_name=_("Value")) fconda_neg = models.BooleanField(null=False, blank=False, default=False, verbose_name=_("Negate")) UI looks like as below: ========================================= admin.py looks like as below: class FilterCondAAdmin(admin.TabularInline): model = FilterCondA class FilterAdmin(admin.ModelAdmin): inlines = [FilterCondAAdmin] I want to check that user has added any conditions or not in filter or blank filter has been created. I want to stop user 2from creating blank filter. Thanks in advance -
Database not exist in docker compose on windows debian subsystem
I want to try to dockerize my Django project, but I face a problem that the database doesn't exist. I run docker on WSL2. I use PostgreSQL. -
iframe refused to connect in django 4.0.2 template
I tried to add iframe to my template in django but it shows me this error: I tried to add X_FRAME_OPTIONS = 'SAMEORIGIN' to my settings.py like explained here: https://docs.djangoproject.com/en/4.0/ref/clickjacking/ but it didn't work, any idea ? Screen Shot my settings.py from pathlib import Path MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] X_FRAME_OPTIONS = 'SAMEORIGIN' -
How to import apps in django from parent directory of manage.py
I have project structure as below: |-Project/ | |-apps/ | | |-notes/ | | |-todo/ | |server/ | | |-api/ | | |-manage.py I want to import apps from ./apps/ folder; tried relative imports with ".." but it doesn't work... eg. INSTALLED_APPS = [ "" '..apps.notes', "" ] how to make parent directory of manage.py as root directory for app imports?