Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot run django migrations
I have a mysql database. On this database, I have tried to create an account and then grant that account permissions to create a test database and standard database. To look at permissions, I use the following: SHOW GRANTS FOR 'broker_admin'@'localhost'; This then produces an output similar to: 'GRANT USAGE ON *.* TO 'broker_admin'@'localhost' 'GRANT ALL PRIVILEGES ON `dbbrokerdata`.`dbbrokerdata` TO 'broker_admin'@'localhost' 'GRANT ALL PRIVILEGES ON `test_dbbrokerdata`.`test_dbbrokerdata` TO 'broker_admin'@'localhost' When I try to run the django app that uses this database, I get the following errors: django.db.utils.OperationalError: (1142, "CREATE command denied to user 'broker_admin'@'localhost' for table 'django_migrations'") django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to user 'broker_admin'@'localhost' for table 'django_migrations'")) Watching for file changes with StatReloader Performing system checks... What do I need to do to the user permissions to get django migrations to work properly ? -
Is there way to confirm user email when user change his email - django
i have option that allow user to change email in his profile but without confirm new email so when he enter new email i want activate email to save it in his profile , how to add confirm i am using UserCreationForm models.py : from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() my code | forms.py : # Profile Form class EmailChangeForm(forms.ModelForm): email = forms.EmailField(required=True,label='Email',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6','placeholder':' Enter Your New E-mail '}) ) class Meta: model = User fields = [ 'email', ] def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('Email is already in use, please check the email or use another email') return email views.py : # Edit Profile View class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): return self.request.user urls.py : from django.urls import path from blog_app.views import SignUpView, ProfileView, ActivateAccount,EmailChange urlpatterns = [ path('profile/change-email/me/', EmailChange.as_view(), name='emailchange'), ] html page : <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="fadeIn fourth" style="background-color:#7952b3" value=" … -
'bytes' object has no attribute 'encode' django web app on Azure
/tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/exception.py in inner response = get_response(request) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/utils/decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/decorators/cache.py in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/utils/decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/contrib/auth/decorators.py in _wrapped_view return view_func(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in dispatch response = super().dispatch(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/generic/base.py in dispatch return handler(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/utils.py in post return super().post(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in post return self.render_next_step(form) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/core.py in render_next_step return super().render_next_step(form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in render_next_step return self.render(new_form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in render context = self.get_context_data(form=form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/core.py in get_context_data rawkey = unhexlify(key.decode('ascii')) im getting this error and i dont know what exactly should i do, i already tried to change rawkey = unhexlify(key.decode('ascii')) to rawkey = unhexlify(key.encode('ascii')) and im still getting the same exact error. im … -
django-rest-framework "This field is required" on POST
Whenever I POST to my django-rest-framework (DRF) endpoints, I keep receiving a "HTTP 400 Bad Request" {"offeror_organization":["This field is required."]} response. But, given the curl example below, I'm clearly specifying a value. This happens regardless of the Content-Type (application/json, application/x-www-form-urlencoded, multipart/form-data). The only time it works is when I submit using the "HTML form" (vs. the "Raw Data") tab on the DRF web interface. There's a few similar SO posts (like this and this), but none of the solutions seem to be working for me. Model: class OrganizationManager(models.Manager): def get_by_natural_key(self, offeror_organization): return self.get(offeror_organization=offeror_organization) class Organization(models.Model): idorganization = models.AutoField(primary_key=True) offeror_organization = models.CharField(max_length=250, null=False, blank=False, verbose_name='Offeror Organization') created_at = models.DateTimeField(auto_now_add=True, null=False) updated_at = models.DateTimeField(auto_now=True, null=False) objects = OrganizationManager() def natural_key(self): return "%s" % (self.offeror_organization) def __str__(self): return self.offeror_organization Serializer: class OrganizationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Organization fields = ['offeror_organization'] # I've tried both with and without a create function def create(self, validated_data): organization_data = validated_data.pop('offeror_organization', None) if organization_data: organization = Organization.objects.get_or_create(**organization_data)[0] validated_data['offeror_organization'] = organization Curl Command: curl -X POST -H 'Content-Type: application/json' -d '{"offeror_organization":"Test2"}' 10.101.10.228:29000/webapp/api/organization/ -
Problem while building path to page with detailed news view
I want it to output all the news when I click on one url, but I can also specify an optional parametric, which, if it exists, will only output the specific news. I can do it. But my navbar in header complains about it. my url: url(r'^news/(?P<year>)',FindNewsView.as_view(), name="news"), error: NoReverseMatch at /news/ Reverse for 'news' with no arguments not found. 1 pattern(s) tried: ['news/(?P<year>)'] <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'news' %}">Новости</a> </div> How do I correct this error? So if I comment out this line, everything will work. I will receive all news or specific news. -
Images and CSS are not being loaded, requires random amount of refresh to load
The problem My company's Django project, running with Nginx and gunicorn, started presenting this issue in the development server. Basically, if I access the app with empty cache, styling files and images are not being loaded at all. Chrome throws the error net::ERR_HTTP2_PROTOCOL_ERROR 200, Safari throws kCFErrorDomainCFNetwork error 303, and Firefox does not throw and error (in fact it gives a 200 for both images and css) but says Stylesheet could not be loaded. However, if I refresh many times the browsers (it could be two times as well as twenty, or more) the images and styles are loaded correctly (one at a time). There are times where some of the images load on first GET request, but it is not a guarantee that those images will be loaded again if I empty cache and refresh. Same setup, different result The funny thing is that on the production server we DO NOT have this problem while both Django settings are the same. The ONLY difference is which DB the apps are pointing to. Both environments have DEBUG set to True. I don't know why prod server has DEBUG set to True, but since it is an app to be used … -
Json in forms.HiddenInput
In project I have a problem with adding json to hiddeninput. When I retrieve a map data in json. I want pass the json to input the form. Works it, when input is visible but I wish it was hidden. I added a widget in form. Unfortunately show me error. | (Hidden field geolokalizacja) This field is required. | forms.py class MapaForm(forms.ModelForm): class Meta: model = Mapa fields = ('geolokalizacja',) widgets = {'geolokalizacja': forms.HiddenInput()} html <form action='.' method='post' enctype='multipart/form-data'> {{ create_form.as_p }} {{ point }} {% csrf_token %} <p><input type="submit" value="Dodaj obiekt"></p> </form> <div id="map" style="height: 512px; width: 512px;"></div> js var popup = L.popup(); function onMapClick(e) { popup.setLatLng(e.latlng).setContent( e.latlng.toString()).openOn(map); var json = {'type': 'Point', 'coordinates': [e.latlng.lng, e.latlng.lat]}; var txt = document.getElementById('id_geolokalizacja'); txt.innerHTML = JSON.stringify(json) } In DOM and Style Inspector appeared to me: <input type="hidden" name="geolokalizacja" value="null" id="id_geolokalizacja"> {"type":"Point","coordinates":[21.91454887390137,52.018592439773414]} </input> It looks like an ale has adopted. Please help -
Django ignores if 'add_customer' in request.POST: and saves the form
if all fields are valid my view ignores the if 'add_customer' in request.POST: and goes directly to if Orderform.is_valid(): I cannot change the order because it should read values from field like: if 'add_customer' in request.POST: add_customer_id = Orderform.cleaned_data.get('Customer').ID request.session['add_customer_id'] = add_customer_id return redirect('add_order_view') template: <form action="/backend/ordrer/add/" method="post"> {% csrf_token %} <div class="row g-2 justify-content-md-center"> <div class="col-md-6 pt-2"> <div class="input-group mb-3"> {{ Orderform.Customer }} <input type="hidden" name="add_customer_id" value="{{ item.ID }}"> <button class="btn btn-success mb-3" name="add_customer"><i class="uil-user-plus"></i>Vælg kunde</button> </div> I cannot do write all if '..' two times like: if Orderform.is_valid(): if 'add_customer' in request.POST: add_customer_id = Orderform.cleaned_data.get('Customer').ID request.session['add_customer_id'] = add_customer_id return redirect('add_order_view') else: edit_form = Orderform.save() edit_order_id = edit_form.pk request.session['edit_order_id'] = edit_order_id or is it a common way? -
KeyError DRF when posting
I get KeyError when I post and I don't write either email or telephone. In my code, either email or telephone are required but not both of them. Why is this happening? This is the serializer: class OrderSerializer(serializers.ModelSerializer): class Meta: model = order fields = '__all__' extra_kwargs = { 'email': {'required': False}, 'phonenumber': {'required': False}} def create(self, validated_data): order= Order.objects.create( email=validated_data['email'], phonenumber=validated_data['phonenumber'], food=validated_data['food'] ) This is the model: class Order(models.Model): date = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=200, unique=True) phonenumber = models.IntegerField(unique=True) food= models.ManyToManyField('Food', related_name='orders', blank=True) def __str__(self): return self.food -
How to put multiple instances of the same ModelForm on a webpage in Django 3 (Python 3.8)?
I am currently trying to make a webpage that displays multiple instances of the same form on a webpage, in which each form will correspond to a different instance of a model. I have made a simplified hypothetical situation to try and explain... So, for example, you have a django app with two models that store information about people's pets. One is called Species and it stores the breed, height, and weight of the pet, and the other is called Dog and it stores the Species (ForeignKey), name, and location. models.py: class Species(models.Model): breed = models.CharField(max_len=50) height = models.CharField(max_len=50) weight = models.CharField(max_len=50) def __str__(self): return self.breed class Dog(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) name = models.CharField(max_length=50) location = models.CharField(max_length=50) def __str__(self): return self.name Now lets say you already have a dictionary containing the name and breed of a bunch of pet dogs, and now we need to take the user to a page that has a form for each dog in the provided list, so that the location of the dog can be put in. This is the part that I don't know how to do... In my forms.py I created a ModelForm that has all the fields from my model, … -
Why is my Django e-commerce project registering multiple orders for each order made?
I am learning Python by building a simple e-commerce store using Django. I've been following this tutorial for guidance. When I pass an order on the site (on localhost), the order is registered 2 times in the backend. Ie: Order #1, Order #2 in the admin panel. I am wondering how I can merge both so 1 order passed on the site = 1 order on the dashboard? In order 1, the field complete is set to True and the Transaction is filled. In order #2, the Pickup time & Type are both set. Models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=100, null=True) CHOICES = (('in-store','in-store'), ('curbside','curbside')) pickup_type = models.CharField(max_length=10, choices=CHOICES) pickup_time = models.DateTimeField(null=True, blank=False) View.py def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] products = Product.objects.all() context = {'products': products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) total = float(data['form']['total']) order.transaction_id = transaction_id if total == float(order.get_cart_total): order.complete = … -
How to link already uploaded image in django db
I want to avoid file duplication for if user already have uploaded an image file in db. Django ImageField adds an suffix to the image file if the file already exists. I tried using the solution given by allcaps in following question: Use already uploaded image in Django's ImageField But it only gives me an drop-down option in the upload section, but it doesn't contain anything. -
ImportError: cannot import name 'Flow' from partially initialized module 'firstapp.models.flows' (most likely due to a circular import), how to design
I have a problem, probably in my design. In my Django project I have a 'Flow' object with 'event_reason' field in it, Foreign key to 'Event' object, therefore I need to import Event object, (otherwise I get the error: Cannot create form field for 'event_reason' yet, because its related model 'Event' has not been loaded yet). Therefore my code of my models is (in models/flows.py) from .events import Event class Flow(models.Model): amount = models.DecimalField(max_digits=17, decimal_places=2, default=0.0) flow_type = models.IntegerField(default=-1, choices=FLOW_CHOICES) ... event_reason = models.ForeignKey('Event', on_delete=models.DO_NOTHING, default=None, related_name='events_flow',blank=True, null=True) In addition I have 'amount' and 'flow_type' fields in the 'Flow' objects and I want that the 'post_save' signal will save a new Flow associated to this Event. Therefore the Event model code is (in models/events.py): from .flows import Flow class Event(models.Model): ... amount = models.IntegerField(default=0) flow_type = models.IntegerField(default=-1, choices=FLOW_CHOICES) @receiver(post_save, sender=Event) def my_handler(sender, **kwargs): new_flow = Flow.objects.create(...) And I get the error ImportError: cannot import name 'Flow' from partially initialized module 'firstapp.models.flows' (most likely due to a circular import) I understand that I cannot my a circular import but I want this functionality to work. How to solve this problem? Should I design the objects otherwise? Thank you -
Django formset get field and update it
I have a formset which provides my articles in a row: class OrderItems(models.Model): ID = models.AutoField(primary_key=True) Item = models.ForeignKey('Products', on_delete=models.DO_NOTHING) Quantity = models.IntegerField('Quantity') UnitPrice = models.DecimalField('UnitPrice', max_digits=10, decimal_places=2) TotalPrice = models.DecimalField('TotalPrice', max_digits=10, decimal_places=2) OrderNo = models.ForeignKey('Orders', on_delete=models.DO_NOTHING) and the formset: Itemformset = Itemform(queryset=OrderItems.objects.filter(OrderNo__OrderNo=order_no_int, OrderNo__UserID=request.user.id), form_kwargs={'user': request.user.id}, initial=[{ 'Item': product.ID, 'Quantity': 1, 'UnitPrice': product.Price, 'TotalPrice': product.Price} for product in choosen_products ]) So normaly if I update the quantity I will on a regular form save the field data in session and load it again for the totalprice field. But if I have more then one articles the formset adds a prefix to every formset, and I can't access the field anymore becuase every field gets a own ID. How would it be possible to update the total price if I change the quantity? <div class="input-group bootstrap-touchspin"> {{ items.Quantity }} <button class="btn btn-success" name="update_quantity"><i class="uil-sync"></i></button> </div> view: if 'update_quantity' in request.POST: updated_quantity = Orderform.cleaned_data.get('form-0-Quantity') request.session['Updated_Quantity'] = updated_quantity return redirect('add_order_view') It saves fine in the model with quantity and total price because I overwrite the field for now but I want also display the total price in the template. -
Browsable API: Requests through HTML form work, but not through Raw Data
In Django, I have create and update methods in serializers.py and I'm testing them through the browsable API in the django admin interface. However, when I try to make a PUT request through the Raw Data form, it doesn't actually call the update method I have written. However, when I try to make a PUT request via the HTML form, it does actually call the update method. Does anyone know why this is? I'm using Django==3.1.6 djangorestframework==3.12.2 -
Django - querying by a for loop
I have to fetch the total wrote posts number by each user @staff_member_required def counter(request): posts = Post.objects.all().count() users = User.objects.all() for user in users.iterator(): written_posts = Post.objects.filter(author=user).count() context = {'users': users, 'written_posts': written_posts, 'posts': posts} return render(request, 'account/counter.html', context) But it returns me for all users the same user's number of posts. Anyone can give a piece of advice? -
Django3: How to setup OneToOneField that works with inline admin correctly?
I would like to create a pipeline instance and create the corresponding input file together. My models I have a structure like this. class Pipeline(models.Model): input_file = models.OneToOneField( 'InputFile', on_delete=models.CASCADE, null=False, parent_link=True ) class InputFile(models.Model): pipeline = models.OneToOneField( 'Pipeline', on_delete=models.CASCADE, null=False, parent_link=False ) I tried different combinations of parent_link=True/False, but nothing worked. Only if I set parent_link=True everywhere both instances are created, however, then it is impossible to delete them again. My admin.py looks like: class InputFileAdmin(admin.StackedInline): model = InputFile class PipelineAdmin(admin.ModelAdmin): inlines = [Inputfile] admin.site.register(Pipeline, PipelineAdmin) Whatever combination I always get errors either during creation or deletion. -
Django - Optional field with Serializer
I want to automatically generate the "path" field of my model when I use the create method of my serializer. Otherwise I would like to be able to pass this field in my request to be able to modify it later. I haven't found a way to make a single field of my template optional. Here is my model : models.py class Shop(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(blank=True, null=True) path = models.CharField(max_length=255, unique=True) mustBeLogged = models.BooleanField(default=False) deliveries = models.FloatField(default=7) def __str__(self): return self.name Here is my code : serializer.py class ShopSerializer(serializers.ModelSerializer): class Meta: model = Shop exclude = ['path'] def create(self, validated_data): path = validated_data["name"].replace(" ", "-").lower() path = unidecode.unidecode(path) unique = False while unique == False: if len(Shop.objects.filter(path=path)) == 0: unique = True else: # Generate a random string char = "abcdefghijklmnopqrstuvwxyz" path += "-{}".format("".join(random.sample(char, 5))) shop = Shop.objects.create(**validated_data, path=path) shop.save() return shop views.py def post(self, request): """For admin to create shop""" serializer = ShopSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) -
Accessing model field in ManyToMany relation in Django
I am following the example in the documentation: https://docs.djangoproject.com/en/3.2/topics/db/models/#extra-fields-on-many-to-many-relationships from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) In this case, given a Person object, how can I access all the groups that Person is in? -
What is the best way to remove a third-party Django app with models in database?
I have a third-party application in my Django project that I'd like to remove. My problem is that if I simply remove it from INSTALLED_APPS, all the models and associated tables that it created in my database will be kept. I know I can manually DROP thoses tables afterwards but I'm wondering if there is a recommended or "clean" way to do so with Django migrations. I created a migration file in one of my apps (the one that used this third-party app) with a migrations.DeleteModel(name='ThirdPartyModel') but it fails to execute because this model is managed by the other app. What is left it to write a RawSQL migration whith a DROP TABLE thirdpartyapp_thirdpartymodel and a DELETE FROM django_content_type WHERE app_label = thirdpartyapp AND model = thirdpartymodel. Is there any other options? How is this type of operations supposed to be done? I'm using Django 3.0. -
GeocoderUnavailable at /
I was doing a Django project that can measure the distance between user and the user's inputted location. For this, I installed geopy and geoip2. Here is my views.py file. from django.shortcuts import render,get_object_or_404 from .models import Measurement from .forms import MeasurementModelForm from geopy.geocoders import Nominatim from geopy.distance import geodesic from .utils import get_geo # Create your views here. def calculate_distance_view(request): obj= get_object_or_404(Measurement,id=1) form=MeasurementModelForm(request.POST or None) geoloactor = Nominatim(user_agent='measurements') ip = '100.37.240.15' country, city, lat, lon = get_geo(ip) #print(country) location = geoloactor.geocode(city) #print('###',location) pointA=(lat,lon) if form.is_valid(): instance = form.save(commit=False) destination_ = form.cleaned_data.get('destination') destination = geoloactor.geocode(destination_) #print(destination) d_lat=destination.latitude d_lon=destination.longitude pointB=(d_lat,d_lon) distance = round(geodesic(pointA,pointB).km,2) instance.location = location instance.distance= distance instance.save() context={ 'distance':obj, 'form':form, } return render(request,'measurements/main.html',context=context) But when I open my browser for the most time it shows this error: GeocoderUnavailable at / HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Max retries exceeded with url: /search?city=New+York&format=json&limit=1 (Caused by ReadTimeoutError("HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Read timed out. (read timeout=1)")) or It Sometimes show different error like: GeocoderInsufficientPrivileges at / Non-successful status code 403 I also tried Photon instead of Nominatim. And the most ridiculously things is that it may work after sometimes. I reckon try and catch might resolve the problem, but I want to know why those errors are occurred … -
How to handle flow of data between groups?
I am building a Django project that lets business owners track their order status. As in, if there is an order of 50 items. The business owner needs to track what is the current status of that specific order. Possible status include : Received Added to cart (at the godown) Packed Bill Generated Dispatched etc Now, each of these statuses will be updated by different users (with appropriate permissions of the group they have been added to). How can I specify the flow of data update. As in, if 'Orange is the group that has appropriate permissions to update the status as 'Added to Cart' and 'Blue' is to update the status as 'Packed' then how can I make sure the person in the 'Blue' group cannot view the order details until the user with 'Orange' group has not updated the status as 'Added to Cart' This is my first question on stackoverflow so if there is any information that you think is missing please let me know. -
How to rename Django settings directory?
By default when creating a new project in Django with: apps/# django-admin startproject example it creates a root directory using the project name: /apps/example/ and inside this root directory it creates a directory with the same name, containing the settings files for the whole project: apps/example/example/ How can I rename the settings directory from apps/example/example/ to apps/example/config/? -
Python list does not work in django with ChartJS
I'm creating a web application where I need to create a few charts. I'm using django 3 and ChartJS. I have created one list for the labels and one list for the data to be inserted into ChartJS. The problem I'm having is that no matter what I try or do the data just will not show up in the graph. When I try to access the data by writing it on the page it does work, but it does not work at all when inserting it into ChartJS for some reason. According to the ChartJS documentation the data field can receive a list of values so I dont understand why this is not working. I have searched quite a lot for solutions to this using google and stackoverflow and while I found some similar threads on stackoverflow, the solutions did not work for me. I tried converting to json, other ways of inserting the data, using a for loop etc, but nothing seems to work no matter what I do. In the web application the labels and values are dynamically created, but at this time to troubleshoot the problem easier I have just created two lists by hand and … -
Python dict giving KeyError even when the key is present in dict
I created a dict by filtering a model like this: article_name_list = ['article name 1', 'article name 2', 'article name 3'...] article_objs = Article.objects.filter(name__in=article_name_list) article_map = {article.name: article.id for article in article_name_list} It gives a dict as expected, something like this: >>> article_map {'article name 1': 10, 'article name 2': 20, 'article name 3': 30, ....} If I try one of the keys, it works, but doesn't work for another key like this: >>> article_map['article name 1'] 10 >>> article_map['article name 3'] 30 >>> article_map['article name 2'] KeyError: 'article name 2' >>> 'article name 2' in article_map False This is weird because I used the article_name_list to filter the articles, but still one of the articles is showing as not present. I verified that both data types are same (string). But still I am unable to find the issue. Extra test: I also checked by using Ctrl + F and searching 'article name 2', and the key is shown included in the search results (This means there are no invisible or unicode characters). P.S. There are around 200+ items in article_map dict, but this key error is only for some (8) items. I can't skip these items that are not …