Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django If both product and variant models have color model, how to make Product tells which colors can variant has?
I have 4 models, product, variant and color. class Size(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Color(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=400) colors = models.ManyToManyField(Color) sizes = models.ManyToManyField(Size) class Variant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=10, validators=[MinValueValidator(Decimal('0.01'))]) quantity = models.IntegerField(validators=[MinValueValidator(0)]) color = models.ForeignKey(Color, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) In this example a variant can have 1 product, 1 color and 1 size. The problem is the color and size are chosen among all the colors and sizes in the store. I want to limit the color and size in variant to the options of colors and size that were chosen in Product. If there anyway please let me know. Thank you :) -
Django messages not showing in certain views
I have multiple views in which I would like to show success messages when redirected home page after successful functions are performed. I have all the required settings added. I am rendering the views from a separate app to my main app, but all urls are referenced so there should be no issues there either. So I have no idea. My Registration view seems to render the message fine, but the rest don't. I will link the views below. WORKING def user_register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) Customer.objects.create(user=user,first_name=first_name, last_name=last_name, email=email) login(request, user) messages.success(request, "Registration successful, you are now logged in...") return redirect('home') else: register_form = UserRegisterForm() return render(request, 'registration/register.html', {'register_form': register_form}) NOT WORKING def user_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,"You were successfully logged in...") return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {}) def user_logout(request): logout(request) messages.info(request, ("You were successfully logged out...")) return redirect('home') HTML {% if messages … -
'TimeSlot' object is not iterable in Python Django
I have a list called time_slots. It contains objects of class TimeSlot. When I write return time_slots[0] I get an error - 'TimeSlot' object is not iterable. Can someone please help me with it? models.py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return f'Number: {self.number}, category: {self.category}, capacity: {self.capacity}, advance: {self.advance}, manager: {self.manager}' class TimeSlot(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() def __str__(self): return f'Room: {self.room}, from: {self.available_from}, till: {self.available_till}' views.py def fun1(): # Some code print(time_slots) # [<TimeSlot: Room: Number: 4, category: Regular, capacity: 4, advance: 14, manager: anshul, from: 02:00:00, till: 04:00:00>, <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 02:00:00, till: 05:00:00>] print(time_slots[0]) # Room: Number: 4, category: Regular, capacity: 4, advance: 14, manager: anshul, from: 02:00:00, till: 04:00:00 return time_slots[0] GitHub repo link -
Django Postgres- how to query jsonb[] in django
The model I'm trying to query has a jsonb[] field data and looks like this data = [{"id":"1","name":"abc","place":"def"},{"id":"2","name":"xyz","place":"uvw"}] I tried querying it using the solution listed here How to filter JSON Array in Django JSONField The query I'm running: name = MyModel.objects.filter( Q(data__contains=[{"name":"abc"}]) ) This query returns an empty query set. If I change data to [{"name":"abc"},{"name":"xyz"}] , then this query works How do I make this query work with all the keys in the json object? -
How to modify Python code to allow for more than two accounts in accounts.json file
Pastebin for the entire PY: https://pastebin.com/CiSnwSAv I have a accounts. Json file that works with the PY file, but as soon as I try to add more than 2 accounts in accounts.json, the py file gives me an error. The py file is suppose to paste email into the login page textbox. It does all it is suppose to but as the github repo states, it can work with upto 6 accounts, it doesn't work with 3. I hope my question is precise and understandable. accounts.json file works fine with 2 accounts [ { "username": "MY@gmail.com", "password": "12345678765" }, { "username": "MY@outlook.com", "password": "123213423" } ] and here is the part of the PY file that might me causing the issue def loadAccounts(): global ACCOUNTS if ARGS.accounts: ACCOUNTS = [] for account in ARGS.accounts: ACCOUNTS.append({"username": account.split(":")[0], "password": account.split(":")[1]}) else: try: ACCOUNTS = json.load(open("accounts.json", "r")) except FileNotFoundError: print("Please create an `accounts.json` file and try again.") prPurple(f""" [ACCOUNT] Accounts credential file "accounts.json" created. [ACCOUNT] Edit with your credentials and save, then press any key to continue... """) input() ACCOUNTS = json.load(open("accounts.json", "r")) But as soon as I add more than one account, [ { "username": "MY@gmail.com", "password": "34324214" }, { "username": "MY@outlook.com", … -
How do I change the menu sequence from "left to right" to "right to left" in backerydemo?
I can't change the menu sequence from "left to right" to "right to left"! This is need because our first language is Persian and we must read from right to left! I changed the languge in base.py to "fa-IR" and wagtail cms languges to "فارسی". But it didn't work. -
I recieved an already written django project that has worked previously on another machine but when I try to run it nothing happens
This is what happens PS C:\Users\***\Downloads\zapisy.zip\zapisy\zapisy-old\src\main python manage.py runserver PS C:\Users\***\Downloads\zapisy.zip\zapisy\zapisy-old\src\main> I just opened it in vscode, installed some python packets that were required and that's all I tried outputting any kind of error to file however the file came out empty -
Unable to open port on AWS ec2 instance (despite other ports working)
I'm running an EC2 instance on AWS. I'm running apache out of the standard port 80 without issues, and I have an node.js/Express application running out of port 3000 without issue. I'm trying to open up port 8000 on the machine and I'm not able to connect. I'm attempting to run a Django project from 8000. Locally, on my machine, I'm able to run the Django project. When I use the curl command locally, I get data back: curl localhost:8000 That returns a valid HTML page. When I use the netstat command, it shows that port 8000 is being listened to. If I open a new window and attempt to start Django again when the first one is running, I get an error that port 8000 is already in use. So, it looks like things are running properly on the local machine. So that leads me to believe that there is something incorrect with my AWS set up. However, I set up the ports the same way for 8000 as I did for 3000. Here is a screen shot of the Inbound rules: I did set up port 3000 over 2 years ago, so it's possible I'm missing a step, … -
Django encrypted field in REST API
Good afternoon, I have a complex backend in Django that feeds a C# desktop application with information, throughout an API. At this point of development I will have to store passwords that my C# application will need to apply locally for each user. I want to store them encrypted in my database and somehow send it to my C# app. What is the best approach for that? I found some ideas on how to encrypt and decrypt the data, but I'm not comfortable about sending them decrypted by a web service, even if I use some Token authentication before the request. Should I some how make a parallel script for decrypt in my C# app, regarding my encrypt in django? Thank you in advance. -
Can I automatically generate a hash or other identifier to track DRF contract changes?
I have a Django DRF app and an external service that would like to know when the API contracts have changed in order to manage cache and other contract-related changes. Could I generate a hash or identifier automatically that reflects the changes to any API contracts in the service? It doesn't need to be versioned/sequential, just a kind of checksum on the contracts. Note: I'm not looking for a hash of the API data changing, just the "shape" or contract structure of the API. -
Redis as django cache and celery backend
Can I use same redis instance as both django cache as well as celery backend? Does principle of separation of concern applies here? Would there by any side effect of having them inside same instance? -
How can I access the class attribute name via the class itself to improve readability and type hinting in Python?
Suppose you have the following classes: class MyClass: attribute1: str attribute2: int class MySecondClass: another_attribute1: str another_attribute2: int I want to access the string 'attribute1' via the MyClass class. For example MyClass.attribute1.fieldname, but I am cannot find such an option. If something like this is possible, could you please let me know? I will explain two possible use cases below: Use case 1 Suppose I want to create method which updates an instance of MyClass with an instance of MySecondClass. It should return a boolean indicating whether the instance of MyClass is updated. I would like to put all the fields I want to map in a dictionary so I can loop over them. E.g. my_class_instance: MyClass my_second_class_instance: MySecondClass field_map = { 'attribute1': 'another_attribute1', 'attribute2': 'another_attribute2' } updated = False for field1, field2 in field_map.items(): current_value = getattr(my_class_instance, field1) new_value = getattr(my_second_class_instance, field2) if current_value != new_value: setattr(my_class_instance, field, new_value) updated = True return updated The main issue that I have with this solution is that it does not take advantage of type hinting or the power of my IDE when I refactor this code. If I would rename attribute1 to attribute_one on the MyClass class, the code would break … -
Django with celery in Docker Env
I have confusion whilst setting up django as docker container. Basically there's celery and celery beat. If i understand correctly celery beat is a scheduler so it needs to be only initialised once. So when horizontally scaling using AWS ECS using docker image i can put django and celery inside same image but not celery beat. Is this assumption correct? -
My submit button is not calling the POST function, I do not know why
This is my page2.html file <form method="post" action="/" class="search-div justify-center align-center text-center form" id="form-change" > {% csrf_token %} <label for="contact-owner">Do you want to check an Email or Phone number?</label> <br> <br> <select name="--select--" id="contact-type" required > <option value="">--Select--</option> <option value="email" id="mail">Email</option> <option value="phone" id="phn">Phone No.</option> <option value="sms-o" id="sms">SMS</option> </select> <br> <br> <label for="contact">Enter Contact : </label> <br> <input type="email" class="search" id="contact_number" required> <br><br> <div id="mail-details"> <label for="subject">Enter Subject of Email : </label> <br> <input type="text" class="search" id="subject" name="subject" required="required "> <br><br> <label for="mail-body">Enter Body of Email : </label> <br> <input type="text" class="search" id="mail-body" name="mail-body" required="required "> <br><br> </div> <div id="sms-details"> <label for="sms">Enter SMS recieved : </label> <br> <input type="text" class="search" id="sms" name="sms" required="required "> <br><br> </div> <div id="after-sub" class="active"> <label for="spam-check">Spam</label><br> <input type="text" id="spam-check" required readonly> <br><br> <label for="risk-score">Risk Score</label><br> <input type="text" id="risk-score" readonly> <br> </div> <button type="submit" id="sub">Submit</button> </form> This is my urls.py def page2(request): if request.method == "POST": print("Test2") return render(request, 'page2.html') print("TEST1") return render(request, 'page2.html') Only TEST1 gets printed. I am not able to enter my request.method=='POST' block. I have tried changing the button types and checking for case sensitivity on the off chance that's my error. -
django page doesn't show anything
My djangp page doesn't show anything `{% extends 'base.html' %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href=" {% static '/css/loginstyle.css' %} "> <h2>Giriş Yap</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> <br> {% csrf_token %} <button type="submit" onclick="location.href='http://127.0.0.1:8000/accounts/signup/'">Sign Up`</button> </form> {% endblock content %}` it doesnt work its show anything -
Django Pyhton: Infinit Scroll feed
I'am working on a Social Media Website, I use Django, Python. I would like to make an Infinit Scroll Paginator to have a User-Friendly Surf experience. For now it shows a Select Bar at the end, f.e. 1, 2, 3, Last. How to make an Infinit Scroll Paginator where it laods when you scroll to the end? feed.html {% if posts.has_other_pages %} {% if posts.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{posts.previous_page_number}}">Previous</a> {% endif %} {% for num in posts.paginator.page_range %} {% if posts.number == num %} <a class="btn btn-info mb-4" href="?page={{num}}">{{num}}</a> {% elif num > posts.number|add:'-3' and num < posts.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{num}}">{{num}}</a> {% endif %} {% endfor %} {% if posts.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{posts.next_page_number}}">Load more Shots</a> <a class="btn btn-outline-info mb-4" href="?page={{posts.paginator.num_pages}}">Last</a> {% endif %} {% endif %} views.py @login_required def posts_of_following_profiles(request): profile = Profile.objects.get(user = request.user) users = [user for user in profile.following.all()] posts = [] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.user.post_set.all() posts.append(p_posts) my_posts = profile.profile_posts() posts.append(my_posts) if len(posts)>0: qs = sorted(chain(*posts), reverse=True, key=lambda obj:obj.date_posted) paginator = Paginator(qs, 6) page = request.GET.get('page') try: posts_list = paginator.page(page) except PageNotAnInteger: posts_list = paginator.page(1) … -
How to Django query only latest rows
I have the following Django models: class Amount(Model): hold_fk = ForeignKey(to=Hold) creation_time = DateTimeField() class Hold(Model): group_fk = ForeignKey(to=Group) class Group(Model): pass Each Group has multiple holds and each Hold has multiple amounts. I have a Group instance. I want to get all the amounts that belong to the group, but I only want the latest one from each hold (newest creation time). How do I accomplish that using Django? -
Wagtail filter by related model field in PagesAPIViewSet
I have EntryPage model that have M2M relation to Category (categories field name). I've added viewset for Entries: class EntriesViewSet(PagesAPIViewSet): base_serializer_class = EntryPageWithSiblingsSerializer model = EntryPage body_fields = PagesAPIViewSet.body_fields + EntryPageWithSiblingsSerializer.Meta.fields listing_default_fields = PagesAPIViewSet.listing_default_fields + EntryPageWithSiblingsSerializer.Meta.fields detail_only_fields = ["prev_entry", "next_entry"] Now I want to be able to filter entries by Category's name. Like following: /wt/api/nextjs/v1/blog_entries/?categories__name=name. Is there easy way to do that using existing FilerBackends, or I need to write my own? -
Dynamic number of forms in a Django formset
I have a Django page where the user fills different forms, specifically 1 form to create a MyModel object and many forms to create many objects (CustomValue object) that are related to MyModel with ForeingKey: class CustomValue(models.Model): mymodel = models.ForeignKey(etc..etc..) Considering that many forms are identical I used a Formset: CustomValueFormSet = modelformset_factory(CustomValue, fields=[...], widgets={...} form=CustomValueModelForm, extra=1 ) Everything till here works as intended. The problem is that in the page the number of forms in the formset can't prederminated (so I don't know what to do with the extra paramenter in CustomValueFormSet). This is because in my template the number of forms (CustomValueModelForm) depends on another iterable. I'm trying to achieve something like this: {% for thing in many_things %} {{thing}} {{formset_instance}} {% endfor %} But considering that formsets are iterables and in my case there's just one form in the formset I had to write like this: {% for thing in many_things %} {{thing}} {% for form in customvalue_formset %} {{form}} {% endfor %} {% endfor %} On the page everything is rendered fine, for every thing I have a CustomValueModelForm instance right below. The problem arise when hitting the submit button, only the last instance CustomValueModelForm gets … -
Is there any way to iterate the dictionary items in django?
How to iterate the items of the dictionary in django ? I am developing the Flight Reservation Website using Django. I developed the Passenger Model in models.py as shown below class Passenger(models.Model): # Constants in Django Model ONE_WAY = "OW" MULTI_CITY = 'MC' ROUND_TRIP = 'RC' TRAVEL_CLASS = ( (ONE_WAY, 'one_way'), (MULTI_CITY, 'multi_city'), (ROUND_TRIP, 'round_trip'), ) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField(max_length=200) trip_choice = models.CharField(max_length=2, choices=TRAVEL_CLASS, default=ONE_WAY) flying_from = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='start', null=True) flying_to = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='destination', null=True) def __str__(self): return self.first_name I wrote the views.py as shown below def passenger(request): passenger = Passenger.objects.filter(id=1) context={} context['passenger'] = passenger context['name'] = 'passenger' return render(request, 'passengers.html', context) templates/passengers.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Passenger Information</title> </head> <body> {% if passenger %} <h1>User is there</h1> {% for key, value in passenger.items %} <li>{{key}} -- {{value}} </li> {% endfor %} {% else %} <h2> No User</h2> {% endif %} </body> </html> -
Sentry + Django: unable to assign tag to event
I'm trying to set up logging for a Django application using Sentry. And I want to use custom tags. I try to assign a tag in the before_sent method for each one event, but these tags do not appear on the self-hosted Sentry. import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration def before_send(event, hint): with sentry_sdk.push_scope() as scope: scope.set_tag('test_tag', 'some_test') return event sentry_logging = LoggingIntegration(level=logging.INFO, event_level=logging.INFO) sentry_sdk.init( dsn=**my_dsn**, integrations=[ DjangoIntegration(), sentry_logging, ], traces_sample_rate=1.0, before_send=before_send, ) After assignment, I can find tags in scope, but events on the Sentry server do not have these tags. I also tried assigning tags to the middleware: from django.utils.deprecation import MiddlewareMixin from sentry_sdk import push_scope class SentryLogMiddleware(MiddlewareMixin): def process_response(self, request, response): with push_scope() as scope: scope.set_tag('test_tag', 'some_test') return response I also tried using set_tag without push_scope and assigning a tag immediately after the exception. None of this helped me to assign tags to events. But I really want to use them for filtering. What didn't I notice? I will be glad for any hints. -
Forbid Google to display others routes of my website
I'm using DigitalOcean to host an Ununtu VM on which I deployed a website. I'm using React and Django + Gunicorn. My frontend has several routes such as www.mywebsite.com/gallery, www.mywebsite.com/projects, etc ... My problem is that when looking up my website in Google, I find routes which don't exist in my frontend nor in my backend, for example www.mywebsite.com/tag/bali, i don't even have a /tag route (when clicking on it i get redirected to /home thanks to the Navigate component from React router) How can I fix this ? Is it possible to allow Google to only see www.mywebsite.com/home? I tried using the Navigate component from React router, hoping it would fix it, it didn't work. -
How to handle django import-export 'matching query does not exist.' error?
I am using import-export library and trying to add import functionality in admin panel. Resource: class DictCitizen_FisResources(resources.ModelResource): id = fields.Field( column_name='№', attribute='id', ) country_name = fields.Field( column_name='Name', attribute='dict_citizen', widget=ForeignKeyWidget(DictCitizen, field='sname') ) fis_id = fields.Field( column_name='Element Code', attribute='fis_id', ) class Meta: model = DictCitizen_Fis fields = ('id','country_name', 'fis_id',) import_id_fields = ('id',) As u can see, one of the fields in ResourceClass (country_name) has ForeignKeyWidget, which means that when importing data from file - model relation is going to be created. The problem is that, information in the file that i import from, does not always matches ForeignKeyWidget model data that is already in database and as a result i get next errors when trying to imoprt from admin panel: Same error written as a text: Номер строки: 25 - DictCitizen matching query does not exist. 25, БОЛИВИЯ, 238 Traceback (most recent call last): File "C:\venvs\abit\lib\site-packages\import_export\resources.py", line 737, in import_row self.import_obj(instance, row, dry_run, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\resources.py", line 557, in import_obj self.import_field(field, obj, data, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\resources.py", line 540, in import_field field.save(obj, data, is_m2m, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\fields.py", line 119, in save cleaned = self.clean(data, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\fields.py", line 75, in clean value = self.widget.clean(value, row=data, **kwargs) File "C:\venvs\abit\lib\site-packages\import_export\widgets.py", line 423, in clean return … -
Pass a class member via parameterized.expand
Is it possible to pass a object created in setUpTestData to a test via parameterized.expand? -
Django Javascript to Check Username Availability
I am working on a Django site with django-tenants and I want to check if a username has already been used when new users are signing up for an account. I am a newbie to django and I don't have much experience with javascript. I am attempting to adapt some code I was able to get to work in another site. Currently, I am getting the following error in the console when the ajax call is made: http://localhost:8000/ajax/check-username-email/?username=ad 404 (Not Found) Here is the relevant code: view: # used to create form for adding company (tenant) accounts class CreateTenantView(SuccessMessageMixin, CreateView): form_class = TenantForm template_name = 'public_site/add_tenant.html' success_message = "Company Created Successfully!" success_url = "/join" def form_valid(self, form): user = User.objects.create_user( username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password'), full_name=form.cleaned_data.get('full_name'), email=form.cleaned_data.get('email') ) self.object = form.save(commit=False) self.object.schema_name = unique_slug_generator(self.object, form.cleaned_data.get('company_name')) self.object.user = user self.object.save() domain = Domain() domain.domain = self.object.schema_name domain.tenant = self.object domain.is_primary = True domain.save() self.domain = domain subdomain = self.object.schema_name host = self.request.META.get('HTTP_HOST', '') scheme_url = self.request.is_secure() and "https" or "http" url = f"{scheme_url}://{subdomain}.{host}" with schema_context(self.object.schema_name): User.objects.create_superuser( username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password'), full_name=form.cleaned_data.get('full_name'), email=form.cleaned_data.get('email'), employee_type=None ) return HttpResponseRedirect(url) def check_username_email(request): username = request.GET.get('username') username_exists = Tenant.objects.filter(username=username).exists() email_exists = CustomUser.objects.filter(email=username).exists() context = { 'username_exists': username_exists, 'email_exists': email_exists, } return …