Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make changes or add column in model for which migration has already been run?
I have already run migration for class Siginingauthlist(models.Model): employee_id = models.AutoField(primary_key=True) employee_name=models.CharField(max_length=500) department_sign=models.CharField(max_length=10) year_validfrom=models.DateField() year_validthrough=models.DateField() def __str__(self): return self.department_sign i forgot to add sign_designation=models.CharField(max_length=50) later class Siginingauthlist(models.Model): employee_id = models.AutoField(primary_key=True) employee_name=models.CharField(max_length=500) department_sign=models.CharField(max_length=10) sign_designation=models.CharField(max_length=50) year_validfrom=models.DateField() year_validthrough=models.DateField() def __str__(self): return self.department_sign makemigrations and migrated again but the column was not added to the table . what can i do -
Python, Django, save files localy with NO ROOT but custom rights
I'm working on a Django app and try to save file with that function def save_entry(title, content): """ Saves an app entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) and I get saved it as with ROOT rights as: -rw-r--r-- 1 root root 18 Aug 27 12:08 Page_test2.md instead: -rwxrwxrwx 1 1000 1000 136 Aug 24 23:16 Python.md* my app doesn't see them in the list for this reason, I suppose def list_entries(): """ Returns a list of all names of encyclopedia entries. """ _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) Please hint me how to solve it -
Django REST Framework "ERR_CONNECTION_REFUSED" on API call
I'm hosting a Django Rest Framework application and a ReactJS website on a Windows 2019 server. The ReactJS communicates to the DRF by API calls. When I browse my website locally (on the server), everything works. However when I access it from my own PC (or any other PC) I'll get the error "ERR_CONNECTION_REFUSED". This is the error I get in my browser when accessing the website from my own PC: I've tried changing the API calls from localhost:8000 to 0.0.0.0:8000, I'll then get a different error saying I can't access the DRF by HTTPS. Django Rest framework console: What's the solution here? -
If the customer wants to add another one product to the previous number of her order list shop in Django
I'm trying to solve a small project. In one section of it, there is a function that will check if status is equal to the shopping and the product already exists in customer's order list and has an amount, try to add a new amount to it. For example john's list has: 3 apple and now wants to add 2 more apples to the list. how we can do it? I did a little bit of it but I'm not sure if it's correct. class Product(models.Model): code = models.CharField(max_length=10) name = models.CharField(max_length=10) price = models.PositiveIntegerField() inventory = models.IntegerField(default=0) class Customer(models.Model): user = models.OneToOneField(to=User, on_delete=models.PROTECT) phone = models.CharField(max_length=20) address = models.TextField() balance = models.PositiveIntegerField(default=20000) class OrderRow(models.Model): product = models.ForeignKey(to=Product, on_delete=models.PROTECT) order = models.ForeignKey("Order", on_delete=models.PROTECT) amount = models.PositiveIntegerField() class Order(models.Model): # Status values. DO NOT EDIT class Status(models.IntegerChoices): STATUS_SHOPPING = 1 STATUS_SUBMITTED = 2 STATUS_CANCELED = 3 STATUS_SENT = 4 customer = models.ForeignKey(to=Customer, on_delete=models.PROTECT) order_time = models.DateTimeField() total_price = models.PositiveIntegerField() status = models.IntegerField(choices=Status.choices) rows = models.ForeignKey(OrderRow, on_delete=models.PROTECT, related_name='order') @staticmethod def initiate(customer): pass def add_product(self, product, amount): self.status = self.status.STATUS_SHOPPING try: if self.orderrow_set.filter(product=product).exists(): pass -
Django - Wrong datetime on server
I've deployed my Django application on DigitalOcean server. Everything works fine, except date. So, hours are displaying different (inside the document time is displaying 4 hour late) on admin dashboard and inside the model instance. During export to excel time also wrong. P.S: I'm using flatpickr for DateTimeField: var d = new Date($.now()); window.addEventListener("DOMContentLoaded", function () { flatpickr(".datetimefield", { enableTime: true, enableSeconds: true, dateFormat: "Y-m-d H:i:S", time_24hr: true, locale: "az", defaultDate: `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}:00` }); }); -
Can't import 'views' from 'urls' - Django
I'm trying to import 'views' file to my 'urls' so I could map the path to this 'vehicle_validation' function. For some reason, pycharm can't find this file. can someone help me understand what's the problem? urls file: from django.urls import path from vehicule_approver import views # error here urlpatterns = [ path('admin/', admin.site.urls), path('vehicle_validation/', views.vehicle_validation) ] views file: import requests from django.http import HttpResponse import json from pyapi.vehicule_approver.models import Vehicle def vehicle_validation(request): ... project structure: structure image -
How do you populate Django models in an SQLite database in an Asynchronous way?
I have a model that I would like to populate with csv data, I have followed a few tutorials on this and am now trying to do it on my own. This is the code that I have so far; import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') import django django.setup() #Import models from app_name.models import Instance # Third Party Imports import pandas as pd # Pull csv data into script file = 'path/to/file/filename.csv' collected_data = pd.read_csv(file,index_col='Timestamp') # this is a dataframe with three columns and a datetime index for timestamp, row in collected_data.iterrows(): info1 = row[0] info2 = row[1] info3 = row[2] inst = Instance.objects.get_or_create(timestamp = timestamp, info1 = info1, info2 = info2, info3 = info3)[0] I am getting the following error, which I don't really understand, as I am quite new to Django. SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Let me know if there is any more information needed for a MCVE -
Django move models classmethod to another file
I have model Order(models.Model): name = models.Charfield() @classmethod do_something(cls): print('do soemthing') What I want to do is to move do_something method from my model to another file.I want to do it because I have several other big methods in this model and want to structure the code, don't like lengh of this file. It's getting big > 700 lines of code. So I want to move my method to another file and import it, so it still can be used like modelmethod like this: Order.do_something() Any ideas? -
django Filter customers in the specific user groups
I want to display Customers from specific groups in the ListView, not able to understand how to get the queryset class CustomerList(ListView): model = Customer queryset = Customer.objects.filter(customer__groups__name__in=['online', 'whatsapp']) template_name = 'staff/customer_list.html' models.py class Customer(models.Model): # Staff customer= models.ForeignKey(User, verbose_name=_("Customer"), on_delete=models.CASCADE, related_name='customer') contact = models.ForeignKey(Contact, verbose_name=_("Contact"), on_delete=models.CASCADE, blank=True, null=True) ... Customers are added to the groups as below: class AddUser(CreateView): def post(self, request, *args, **kwargs): form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) group, created = Group.objects.get_or_create(name='online') user.groups.add(group) user.save() -
Sending 2 JSON objects to Django with Ajax
I'm trying to send 2 arrays via Ajax to my Django backend. They are basic lists of dicts like: send_products = [{'product': some_text, 'orden': some_value}, .........] send_categories= [{'category': some_text, 'orden': some_value}, ........] The AJAX call As I researched around the web, I'm trying data = { 'category': send_categories, 'products': send_products, }; data['category'] = JSON.stringify(data['category']); data['send_products'] = JSON.stringify(data['send_products']); $.ajax({ url:'/website/save-catalog-order/', type:'POST', dataType: 'json', contentType: 'application/json', csrfmiddlewaretoken: "{{ csrf_token }}", data: data, success:function(response){ }, error:function(){ }, }); My target Django view @ensure_csrf_cookie @login_required @transaction.atomic def SaveCatalogOrderView(request): category = request.POST['category'] data = {} return JsonResponse(data) Result: I get an "MultiValueDictError: 'category' If I try category = json.loads(request.POST['category']) Result: I get an "MultiValueDictError: 'category' If I try category = json.loads(request.POST) Result: TypeError: the JSON object must be str, bytes or bytearray, not QueryDict I usualy send 1 Json obeject POSTs without any problem But I can;t find the way to send 2. Any clues welcome! -
django automatic login without being logged in
I wanted to talk about a problem I've been having in one of my latest django builds. I want to make the following automatic login script, but when I provide the link, the application fails to log the user in, however, even with debug = True set in settings, it will not provide me with any errors, it simply refuses to log me in. I have created a superuser, which I call "User1" in this case. def automatic_login(request): user = User.objects.get(username="User1" login(request, user, backend=settings.AUTHENTICATION_BACKENDS[0] return HttpResponseRedirect(reverse('student_listing')) I have been tearing hair out as to why this doesn't work, any help would be greatly appriciated! -
ImportError: attempted relative import with no known parent package in context_processor
I have a django-project (version 3.1) with this structure: my_project --my_app --__init__.py --admin.py --asgi.py --context_processors.py --models.py --urls.py --views.py --wsgi.py In my views.py I import a model as follows: from .models import my_table which works perfectly. In my context_processors.py I do exactly the same thing: from .models import my_table but this gives me the error: ImportError: attempted relative import with no known parent package. This does not make sense to me. Can anyone help me out on this? -
Django Drop-down fields for foreign key to another database field
I am a Django beginner and I am having trouble using bootstrap drop-downs for foreign key use. I have an input form for adding Providers (supplier, manufacturer, or both) for my purchasing website that has the following data structure: class Provider(models.Model): provider_id = models.AutoField(primary_key=True) provider_name = models.CharField(max_length=255, unique=True) provider_address = models.CharField(max_length=255, null=True, blank=True) provider_email = models.EmailField(null=True, blank=True) provider_contact_01 = models.CharField(max_length=20, null=True, blank=True) provider_contact_02 = models.CharField(max_length=20, null=True, blank=True) provider_type = models.ForeignKey(ProviderType, on_delete=models.CASCADE) in which provider_type is a foreign key for table ProviderType that has the following data structure: class ProviderType(models.Model): providertype_id = models.AutoField(primary_key=True) providertype_desc = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.providertype_desc Dataset for ProviderType: | providertype_id | providertype_desc | --------------------------------------------- | 1 | Supplier | | 2 | Manufacturer | | 3 | Supplier & Manufacturer | The problem is that I have used providertype_desc as the text in the drop down field, because it is more user friendly and has context, rather than providertype_Id, Code segment in html: <div class="form-group col-md-6"> <label for="provider_type">Type of Provider</label> <select class="custom-select" id="provider_type" name="provider_type" aria-label="Example select with button addon"> <option selected>Choose...</option> {% for prov_types in provider_types %} <option>{{prov_types.providertype_desc}}</option> {% endfor %} </select> </div> But the POST sequence fails because the providertype_id needs to be … -
How to setup Amazon AWS S3 static in Django
I'm trying to setup amazon AWS S3 static Here is my settings.py USE_S3 = os.getenv('USE_S3') == 'TRUE' if USE_S3: # aws settings AWS_ACCESS_KEY_ID = 'AKIAVYBTPX6PETRM7GXR' AWS_SECRET_ACCESS_KEY = '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' AWS_STORAGE_BUCKET_NAME = 'manual.la' AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') I've uploaded my css files to my bucket. And it's available with HTTP: http://manual.la.s3.amazonaws.com/static/css/bootstrap.min.css But when I use the link with HTTPS - it gives a warning: https://manual.la.s3.amazonaws.com/static/css/bootstrap.min.css Here is my html: {% load static %} <html> <head> <link href="{% static 'css/bootstrap.min.css' %}" rel='stylesheet'> </head> Can anyone help me with this? Thank you -
MySQL 5.7+ is required to use JSONField
I was initialising my django project to pythonanywhere.com but while i was migrating i saw this error. (django_mysql.E016) MySQL 5.7+ is required to use JSONField HINT: At least one of your DB connections should be to MySQL 5.7+ I am using JSONField in my models. Can anyone suggest me a fix? Settings.py 'default' :{ 'ENGINE': 'django.db.backends.mysql', 'NAME': '******', 'USER': '****', 'PASSWORD': '*****', 'HOST': '******', 'PORT': '3306', 'OPTIONS': { # Tell MySQLdb to connect with 'utf8mb4' character set 'charset': 'utf8mb4', }, }, -
How to extract JSON value from a list and render it in a django model form?
I am trying to render a Django model form using the below model. The problem is one of the model field is a JSONField. This is a list of length 1 having some JSON data. When I render the model form, the number field renders the list without any issues. But I want to extract the phone value from the JSON inside the list and render it. I have tried extracting it in the template but it is not working as intended. How can I extract the phone value from the JSON and render it in the form? As example, when I render the data for id 1 using my view, I should see 'Client_1' in the name field and '1234567890' in the number field. I am using Django 3.1 and using Django Crispy Forms to render the model form. Data as seen client table in db: id name number 1 Client_1 [{'type': 'mobile', 'phone': '1234567890'}] 2 Client_2 [{'type': 'mobile', 'phone': '3334445555'}] 3 Client_3 [{'type': 'mobile', 'phone': '9876543210'}] models.py: class Client(models.Model): name = models.TextField() number = models.JSONField(blank=True, null=True) forms.py: from .models import Client class ClientForm(forms.ModelForm): class Meta: model = Client fields = '__all__' clients.html template: {% load crispy_forms_tags %} <form … -
Django order by multipe elements
I'm trying to achieve the following with a Django query: { "channel_x":{ "date_x":{ "pl__sum":1 }, "date_y":{ "pl__sum":2 } }, "channel_y":{ "date_x":{ "pl__sum":1 }, "date_y":{ "pl__sum":2 } } } I wrote the following code in an attempt to do so: Tip.objects.values("channel__name", "prediction__fixture__date").filter(prediction__fixture__date__date__lte=datetime.now(), prediction__fixture__date__date__gte=datetime.now()-timedelta(days=6)).order_by('channel__name', 'prediction__fixture__date').annotate(Sum('pl')) But this returns this {'channel__name': 'SB Betting (Live)', 'pl__sum': Decimal('7.730')}, {'channel__name': 'SB Betting (Live)', 'pl__sum': Decimal('-8.460')} How can I achieve the same (or similar) as my example above? -
duplicate key error primary key django and mongo (djongo)
i have some data in my model Paper with id primary key from id = 1 - 30 id field created by django but now when i create new object it want to created with id = 1 then raise a duplicate error i dont have any idea can anybody help me ? -
How can I Build an Django REST API that will judge C, C++, Java and Python codes and return verdict, runtime, memory-used?
I want to build a Django Rest API as a part of my ongoing project, which is mainly an Online Judge. I want to send user-submitted-code, input-file, memory-limit, time-limit, language-type and the API will return me the verdict, memory-used, runtime. Is it possible with Django REST API? If possible, how can I build one? -
Django 2.2 'SafeText' object has no attribute 'get'
I am using Django 2.2 in a project. I am rolling an extra lightweight app that allows users to modify the raw HTML used in a template. This is a cut down example of the function I have written to do that: def show_page(request): from django.template import Context, Template template = Template("<h3>My name is {{ my_name }}.</h3>") context = Context({"my_name": "Adrian"}) return template.render(context) # <- Django barfs at this line I get the exception shown in the title: AttributeError at /show-page 'SafeText' object has no attribute 'get' How do I resolve this error, so I can display the page correctly? -
Create object foreignkey relation
so I have these two models class Recipe(models.Model): short_description = HTMLField(max_length=400) likes = models.ManyToManyField(User, blank=True, related_name='recipe_likes') slug = models.SlugField(blank=True, unique=True) published_date = models.DateTimeField(blank=True, default=datetime.now) ratings = GenericRelation(Rating, related_query_name='recipes') class Ingredient(models.Model): name = models.CharField(max_length=20) amount = models.FloatField() recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='recipe_ingredients') In the admin panel from the recipes section I want to be able to add ingredients for that recipe, what do I need? I think I don't know the right searchterms to use, hope you understand what I mean. Thanks for the help. -
Adding Validation for case insensitivity in Django python
Hi i am learning django Python. In my modals i have added a button which will upload csv file. I have added validation that a csv file must have summary and Test case ID. But i want to know that how to add validation that while uploading csv file uppercase and lower case both should work. I am having error if the s in summary is 'S' i.e in capitals it shows 'CSV file must have "summary" column and "Issue Key" column') but insted it should upload csv file. Modals.py class AICSVFile(models.Model): file = models.FileField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Form.py class CsvUpload(forms.Form): csv_file = forms.FileField() def clean_csv_file(self): value = self.cleaned_data['csv_file'] if not value.name.endswith('.csv'): raise forms.ValidationError('Invalid file type') # Read data from file 'filename.csv' # (in the same directory that your python process is based) # print(dir(value)) # with open(value.file, 'r') as csvfile: try: data = pd.read_csv(value.file, encoding = "ISO-8859-1") # Do whatever checks you want here # Raise ValidationError if checks fail except Exception as e: print('Error while parsing CSV file=> %s', e) raise forms.ValidationError('Failed to parse the CSV file') if 'summary' not in data or 'Test Case ID' not in data: raise forms.ValidationError( 'CSV file must have … -
how to post data to table having foreignkey relation with user model using django rest api
i would like to add data to table which having a foreignkey relatonship with user model through django rest api. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): # username = None email = models.EmailField(verbose_name='email',max_length=50,unique=True) phone = models.CharField(max_length=17,blank=True) REQUIRED_FIELDS = [ 'first_name', 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email class UserInfo(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) address = models.CharField(max_length=50) zipcode = models.CharField(max_length=20) medication = models.CharField(max_length=25) def __str__(self): return str(self.user) serializers.py from djoser.serializers import UserCreateSerializer class UserCreateSerializerCustom(UserCreateSerializer): class Meta(UserCreateSerializer.Meta,): model = User fields = ( 'id', 'email', 'username', 'password', 'first_name', 'last_name', 'phone', ) ## User Additional Info Serializers class UserAdditionalSerializers(serializers.ModelSerializer): user = UserCreateSerializerCustom() class Meta: model = UserInfo fields = ( 'user', 'address', 'zipcode', 'medication', ) views.py class UserAdditionalView(generics.ListCreateAPIView): queryset = UserInfo.objects.all() serializer_class = UserAdditionalSerializers how will i send user instance with the data....?? i'm using token authentication for the api. Which is the best way to achieve this..?? -
Reverse for 'cart_detail' not found. 'cart_detail' is not a valid view function or pattern name
Here is my Add to Cart button HTML:` <a href="{% url 'store:add_cart' product_detail.id %}"> </a> Here is my add_cart view: def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id=_cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart, ) cart_item.save() return redirect('cart_detail') And here's my urls.py for add_cart and cart_detail: app_name = 'store' urlpatterns = [ path('', views.home, name='home'), path('product-list/', views.product_list, name='product_list'), path('cart/', views.cart_detail, name='cart_detail'), path('cart/add/<int:product_id>', views.add_cart, name='add_cart'), path('detail/<slug:product_slug>', views.product_detail, name='product_detail'), path('category/<slug:category_slug>', views.home, name='products_by_category'), ] When I click on add to cart button in my product-detail page: I GET THIS ERROR: Reverse for 'cart_detail' not found. 'cart_detail' is not a valid view function or pattern name. Which points to my view add_property -> return redirect('cart_detail') I tried changing my 'cart_detail' to '/cart' in the views but then it's showing that my cart has no items even though the model objects Cart and Cart Item are created. PLEASE HELP RESOLVE ASAPenter image description hereenter image description here -
Django on Google App Engine Flexible: create and remove files
I have a Django application deployed on Google App Engine (flexible environment). Can I create files and remove files like this: with open('myfile.xls', 'w') as file_object: #writing to file os.remove('myfile.xls') or use NamedTemporaryFile? Now this code works, but after some days after deploying my app become running slowly. It is not about cold start. Redeploying fixes it. Сan files not be deleted and waste disk space? Or there is another reason?