Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framwork validate ListSerializer field from data received by form-data request
I am using Django and DRF to handle a restful backend. A request is sent that contains some fields and data (attached images). The request is received by a DRF serializer. I sent the request using form-data (via Postman). I received all fields and images properly except for a ListSerializer. The field is: class ListSerializerClass(serializers.Serializer): field_1 = serializers.IntegerField() field_2 = serializers.ListField(child=serializers.IntegerField(), min_length=1) class MainSerializerClass(serializers.Serializer): list_serialized_field = InputOfficeTaskTypeMap(many=True) normal_field = serializers.CharField(max_length=50) normal_field = serializers.CharField(max_length=50) Using Postman I send a list_serialized_field as a json: {"code": 123, "list_serialized_field": [{"field_1": 1, "field_2": [1,2]}, {"field_1": 2, "field_2": [2]}] Unfortunately, I could not received validated list_serialized_field and after calling serializer.is_valid, I got error that "list_serialized_field" is required. Is there any way to send json data and files in one request and validate them? P.S: I know that I can send form-data like below: list_serialized_field[0]field_2[0] but I want to send them in JSON format. -
Db error when cloning repository from github
I cloned the repository from github, activated the environment, but when I wrote the migration, appeared error. I tried fix her many times, but nothing worked. return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: api_secret models.py import datetime as dt import pgcrypto from django.db import models LIFE_TIME = ( #some code ) DATE_NOW = dt.datetime.now() TIME_OF_DEATH = { "1": (DATE_NOW + dt.timedelta(days=7)), "2": (DATE_NOW + dt.timedelta(days=3)), "3": (DATE_NOW + dt.timedelta(days=1)), "4": (DATE_NOW + dt.timedelta(hours=1)), "5": (DATE_NOW + dt.timedelta(minutes=30)), "6": (DATE_NOW + dt.timedelta(minutes=5)), } class Secret(models.Model): """The secret model contains all the information about the secret and its data""" secret = pgcrypto.EncryptedCharField("Secret", max_length=100000) key_word = pgcrypto.EncryptedCharField("Pass phrase", max_length=100) is_viewed = models.CharField("Already viewed", max_length=100) slug = models.CharField("Slug", max_length=20, unique=True) lifetime = models.PositiveIntegerField( verbose_name="Lifetime", null=True, blank=True, ) time_of_death = models.DateTimeField( "Secret end time", null=True, blank=True ) created_date = models.DateTimeField("Created date", auto_now_add=True) -
Trying to connect Django to MySQL. Connection error when migrating
I've been working for several weeks on Django. So far I have made 2 small projects. Now I tried to connect Django to the MySQL database. First, I started a new project. Then made a new app and updated the app in settings.py After that changed the database in the same file settings.py with my settings, Made a small model, Installed all the necessary aps, MySQLclient etc, Made the first migration successfully with 'Makemigration' So far so good! Next, I tried to make the second migration, as in the instructions. Then the error message appears: 'error 111, can't connect to database' Made some changes in the settings file, including SQL mode 'strict trans tables'. Now it shows me the error: Can't connect to local MySQL server through socket ... Missing file .sock. I looked up the directory and there was no such file. In the my.conf file the file is different!!! And exists! What is going on and what to do? -
How to legally protect myself from illegal files?
I understand this might not be the forum to ask this question but I'm trying to protect myself and other website users from illegal videos or files. I am doing a website and how do I check if the uploaded file contains any illegal stuff or adult content. Is there any API or service that does this. Also, how do I legally protect myself? Do I need to write something in the privacy policy and what sort of information do I need to collect from the users that upload files, is IP address enough or do I need email addresses as well? -
Create django project
I am new to programming I want to create django application in which user uploads a recipe. And for recipe they select the ingrident from the list and give the quantity of the ingrident. They should give multiple ingrident with quantity of every ingrident and a recipe name . And I also want to display the recipe with details -
This is the error that I am gettig TypeError: unhashable type: 'list'
What I want to do is, I want to create an endpoint through which I can upload a csv file with dataframes and I want to display these dataframes on my custom html format. But I am getting the error while sending file data from backend to frontend. Code def upload_files(request): form = UploadFileForm(request.POST or None, request.FILES or None) if form.is_valid(): csvfile = request.FILES['file_name'] data = pd.read_csv(csvfile.name) json_record = data.reset_index().to_json(orient='records') arr = [] arr = json.loads(json_record) context = {'d', arr} return render(request, 'upload.html', context) return render(request, 'record.html', {'form': form}) Error context = {'d', arr} TypeError: unhashable type: 'list' -
How to manage CORS in Django
Im trying to connect React.js[axios] and Django [hosting in Heroku] and every time I get this Ive allowed my host to connect but it doesn't work CORS_ALLOW_ORIGINS = [ 'localhost', 'https://itbookcom.herokuapp.com/' ] CSRF_TRUSTED_ORIGINS = [ 'localhost', 'https://itbookcom.herokuapp.com/' ] and here is react.js connection part constructor(props) { super(props); this.state = { bookList: [], error: null, }; } refreshList = () => { axios .get('https://itbookcombackend.herokuapp.com/api/books/') .then((res) => this.setState({ bookList: res.data })) .catch((err) => console.log(err)); }; componentDidMount() { this.refreshList(); } -
Parsing array of objects to Django backend from Ajax request
I have some data that I am gathering using JavaScript which I and trying to parse to my Django backend using an Ajax request. However the array is very different when console logging in the JavaScript and printing out in the python back end. JavaScript: function confirm_add_all_product(e) { let data_products = [] let table = e.closest("thead").nextElementSibling.childNodes table.forEach(function(i) { let row = {} row.record_id = (i.children[7].children[1].firstChild.getAttribute('data-record-id')) row.product_id = (i.children[7].children[1].firstChild.getAttribute('data-product-id')) row.foil = (i.children[2].textContent) row.condition = (i.children[3].textContent) row.language = (i.children[4].textContent) row.quantity = (i.children[7].children[0].value) data_products.push(row) }); console.log(data_products) $.ajax({ url: "/integrations/card/inventory_update_all/", type: "POST", data: { csrfmiddlewaretoken: csrf_token, data_products: data_products, }, success: function (response) {}, error: function (request, status, error) { console.log(error); } }); } Python: @login_required def inventory_update_all(request): print(request.POST) return HttpResponse(status=200) JS Console Log: [ { "record_id": "", "product_id": "", "foil": "false", "condition": "nm", "language": "eng", "quantity": "1" }, { "record_id": "", "product_id": "", "foil": "false", "condition": "nm", "language": "eng", "quantity": "2" } ] Current Python Print: <QueryDict: {'csrfmiddlewaretoken': [''], 'data_products[0][record_id]': [''], 'data_products[0][product_id]': [''], 'data_products[0][foil]': ['false'], 'data_products[0][condition]': ['nm'], 'data_products[0][language]': ['eng'], 'data_products[0][quantity]': ['1'], 'data_products[1][record_id]': [''], 'data_products[1][product_id]': [''], 'data_products[1][foil]': ['false'], 'data_products[1][condition]': ['nm'], 'data_products[1][language]': ['eng'], 'data_products[1][quantity]': ['2']}> Expected Python Print: <QueryDict: {'csrfmiddlewaretoken': [''], 'data_products': {['record_id': '', 'product_id': '', 'foil': 'false', 'condition': 'nm', 'language': 'eng', 'quantity': '1'],['record_id': '', 'product_id': … -
Django folder structure for created file, static? media? or another one?
I want to create the file(.wav) by django and let it be downloaded by user. Currently I create the file under /myproj/static directory. However it is mixed with the other jpg/img files, so,, it's not good design? then, I read the document about /myproj/media directory but it is said used for user upload files. So,,, how is the good directory design for server created file? Should I create such as /myproj/create_wav? but how can user access this url in template? Thank you for any idea or helps. -
Not getting the profile image from html form but other datas are getting
this is the profile model class Profile(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) id_user=models.IntegerField() bio=models.TextField(blank=True) profileimg=models.ImageField(upload_to='profile_images',default='defaultdp.png') location=models.CharField(max_length=100,blank=True) def __str__(self): return self.user.username this is the html form <form action="" method="POST" enctype="multipart/form-data"> {%csrf_token%} <div class="col-span-2"> <label for=""> Profile Picture</label> <img height="100" width="100" src="{{user_profile.profileimg.url}}"> <input type="file" name="profileimg" placeholder="" class="shadow-none bg-gray-100"> </div> <form> this is views.py @login_required(login_url='signin') def settings(request): user_profile=Profile.objects.get(user=request.user) if request.method == 'POST': if request.FILES.get('image')==None: image=user_profile.profileimg bio=request.POST ['bio'] location=request.POST['location'] user_profile.profileimg=image user_profile.bio=bio user_profile.location=location user_profile.save() if request.FILES.get('image')!=None: image=request.FILES.get('image') bio=request.POST ['bio'] location=request.POST['location'] user_profile.profileimg=image user_profile.bio=bio user_profile.location=location user_profile.save() return redirect('settings') return render(request,'setting.html',{'user_profile': user_profile}) the profile image which I am getting is the defaultdp.png which is the default pic if no file is getting uploaded. I think the file i am uploading is not getting saved on the database or I dont know what is happening here. could anyone please help me to sort it out..? If I am missing any kind of code snippet here for debugging kindly mention it.I will edit the question with the mentioned code. -
Django - No module named 'mywebsite'
I have a django app that I downloaded from a Github repo where the main app is not called "mywebsite" (like instructed in the django tutorial). Everytime I run python manage.py runserver i get the following error. Conceptually I understand the error, but practically I don't. The issue can't be that I have always need to name my repo "mywebsite" right? This is the current repo structure. Traceback (most recent call last): File "/Users/nicolamacchitella/Documents/GitHub/familytree/.env/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/nicolamacchitella/Documents/GitHub/familytree/.env/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/Users/nicolamacchitella/Documents/GitHub/familytree/.env/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/Users/nicolamacchitella/Documents/GitHub/familytree/.env/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Users/nicolamacchitella/Documents/GitHub/familytree/.env/lib/python3.9/site-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/Users/nicolamacchitella/Documents/GitHub/familytree/.env/lib/python3.9/site-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/Users/nicolamacchitella/Documents/GitHub/familytree/.env/lib/python3.9/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/homebrew/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mywebsite' During … -
Should i allow user to use the admin panel to upload his blog?
I'm building an app for someone, one of its function is it allowers the owner to upload blogs to the website. So i'm wondering if i should create a page for uploading blog or just give him staff permission so he can create and upload it through django's admin panel. I want to know if this is safe or if it will be worth it to create a front-end template for just one person to use. -
WooCommerce webhooks with Django Rest Framework
I am trying to integrate WooCommerce webhooks with Django but without success. I found a solution to a similar issue, but still cant make it work. The thing is that, Woocomerce is generating this secret key automatically. I guess that I have to hard code it by myself in the admin panel ? Also about the code bellow(solution found in the web), Django is complaining that request has no property payload. I guess that it must be data ? mport base64 import hashlib import hmac request_sig = request.headers.get("x-wc-webhook-signature") signature = hmac.new(<your_secret_key>.encode(), request.payload, hashlib.sha256).digest() if hmac.compare_digest( request_sig.encode(), base64.b64encode(signature) ): return True return False enter code here -
django taggit self.tags.add() in not working in django
I am using djagno-taggit. I want to add other fields data automatically when I save the data table. models.py class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) varient=models.CharField(max_length=100, default="") Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="", unique=True, blank=True) tags_char=models.TextField( blank=True) Tags = TaggableManager(blank=True) def save(self, *args, **kwargs): getlast=resource.objects.all().last() getid=getlast.id print(getid) newid=int(getid)+1 if not self.pk: self.pk=newid self.tags_char= self.desc+","+self.size ans=[self.title ,self.desc,self.size] self.Tags.add(*ans) print(self.Tags.all()) for tag in self.tags_char.split(','): print(tag) super(resource, self).save(*args, **kwargs) Here first I get pk for current data and try to save list that has the same data fields in the Tags fields. It works well when I Print Tagsafter adding and get the below result in my terminal when I print(self.Tags.all()) result in the terminal is: <QuerySet [<Tag: tagSize>, <Tag: tagTitle>, <Tag: tagDescription>]> But when I open it in the admin models data table then I got Tags fields empty!! Any solution?? -
4 products on the same line in the template
I'm developing an e-commerce with Django. My backend is fine, my problem is with the template. Currently, I want to display 4 products per row, and if there are 7 products, the other 3 must be aligned with the top one. I'm using bootstrap to do this, however, for some reason I don't know, it doesn't have 4 products on the same line, even with space. I'm using a container with 1200px. home.html <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="row"> {% for product in products %} <div class="card mb-4 border rounded" style="width: 13.5rem;"> <a href="{{ product.get_absolute_url }}"> {%if product.image %} <img class="img-produto" src='/media/{{product.image}}' class="card-img-top hover_img "> {% else%} <img class="img-produto" src="{% static '/img/not-found-product.jpg' %}" class="card-img-top hover_img"> {%endif%} </a> <div class="card-body"> <p class="card-title">{{product.name}}</p> <p class="card-text"><i class='fas fa-dollar-sign' style="margin-right:2px"></i>{{product.price}}</p> </div> </div> {% endfor %} </div> </div> </div> </div> base.css @media (min-width: 900px){ .container{ max-width: 1100px; } } -
i could not run my django project which has been cloned from git why
Exception in thread django-main-thread: django.core.exceptions.ImproperlyConfigured: WSGI application `enter code here`'vivawalleetintegration.wsgi' could not be loaded; Error importing module# -
Django model auto update status when the medicine is expired
How to Auto update the status when the medicine is expired? for example, I created medicine record and set the expirationdate to july 2022, if the current date is greater than the expirationdate it will update the status of medicine to "Expired", How do I do that? class Medicine(models.Model): medstatus = [ ("Expired", "Expired"), ("Active", "Active") ] description = models.CharField(max_length=50, null=True) expirationDate = models.DateField(null=True) status = models.CharField(max_length=50, choices=medstatus, null=True) -
I change the error message, but it doesn't change
I change the error message in the model, but it doesn't change. I can't understand why this approach doesn't work, because it works for other fields it's my model class CustomUser(AbstractUser): username = models.CharField( max_length=15, unique=True, validators=[UnicodeUsernameValidator()], error_messages={ "unique": "Test login", }) group = models.OneToOneField('Group', unique=True, on_delete=models.CASCADE, error_messages={ "unique": "Test group" }) email = models.EmailField(models.EmailField.description, unique=True, validators=[email_validator], error_messages={ "unique": "Test email", }) def __str__(self): return self.username and it's my Group Model class Group(models.Model): name = models.CharField(max_length=20, unique=True) faculty = models.ForeignKey(Faculty, on_delete=models.CASCADE) def __str__(self): return self.name When testing in postman, I get this: { "username": [ "Test login" ], "group": [ "This field must be unique." ], "email": [ "Test email" ] } Thank you in advance -
Create User in django using Rest Framework
i've seen people using different ways to create user in django Rest framework. i tried & none of them is working for me. sometimes it says Key error: Groups or something else. so i tried this without having a is_valid & it works like a charm. is this a safe way to use to create user or if not why & how should i create User in views? #my views.py @api_view(['GET','POST']) def getUserData(request): if request.method == 'POST': user = User.objects.create_user( username=request.data['username'], password=request.data['password']) serializer = userSerializer(user) return Response(serializer.data) -
Access value of Django widget attribute
I have Django Form Field: dob = forms.DateField( required=True, widget=NumberInput( attrs={ "type": "text", "class": "datepicker", "autocomplete": "off", "placeholder": "DD/MM/YYYY", } ), ) Now I need to access the "placeholder" value. I use datepicker to change the format: $('.datepicker').datepicker({ format: 'mm-dd-yyyy',# **here I need to replace it with Django widget attribute.** }); How can I get the value of the placeholder so I can do something like that: $('.datepicker').datepicker({ format: {{django.placeholder | safe}}, }); -
django import tags error Line number: 1 - resource objects need to have a primary key value before you can access their tags
I am using django taggit in my models and trying to import data. But getting errors. Given below. Line number: 1 - resource objects need to have a primary key value before you can access their tags. models.py: class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) varient=models.CharField(max_length=100, default="") Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="", unique=True, blank=True) Tags = TaggableManager(blank=True) -
Django trigger add on models
In adminsite, I want if the user create an account on Student table, it will also add to the dashboard table, how can i do that? class Dashboard(models.Model): fullname = models.CharField(max_length=50,blank=True, null=True) status = models.CharField(max_length=50,blank=True, null=True) dateCreated = models.DateTimeField(default=datetime.now()) class Student(models.Model): Gender = [ ('Male', 'Male'), ('Female', 'Female') ] fullname = models.CharField(max_length=50, null=True) status = models.CharField(max_length=500, null=True, default='Student') contact_number = models.IntegerField(max_length=50, null=True) age = models.IntegerField( null=True) gender = models.CharField(max_length=50, choices=Gender, null=True) birthdate = models.DateField(max_length=50, null=True) class Meta: verbose_name_plural = "LIST OF STUDENTS" -
How do I load local directory into path in urls.py
I saved my homepage.html file in my laptop see this image D:\Python\WebDjango\BaseCoffeehouse\coffeehouse\templates. Then in urls.py (open in VSCode), I added the path as below : path('D:/Python/WebDjango/BaseCoffeehouse/coffeehouse/templates', TemplateView.as_view(template_name='homepage.html'), name='homepage'), When I run the server (python manage.py runserver), I got an error message "Page not foung 404" in the default port 8000. So, how should I do it to open my homepage.html file? -
Why my images are missing when deploying django and postgresql on heroku?
I create a webapp with Django for the backend and React for the frontend. I deploy the app on heroku and I use the heroku-postgres as the database, after deployin the app everything works perfectly (superuser, models.py etc...). Now I connect to the superuser account and try to add data, all data is displayed on the application frontend except the images. Note that I have a static folder and also I have run python manage.py collectstatic before deploying the app on Heroku. What can I do to make the images displayed every time I add them? -
Django Mailgun API returning 401 forbidden
I've installed Django any mail and am I trying to use mail gun with it for password resets. I've added any mail to my installed apps and tried to use mail gun as an API or smtp service. Both return back 401 forbidden For using mail guns API here's my code: EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" ANYMAIL_MAILGUN_API_KEY = config("MAIL_GUN_DOMAIN_API") For MAIL_GUN_DOMAIN_API I tried using my accounts private key and I tried creating a domain and using the domains sending key. Both returned the same response. for smtp : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mailgun.org' EMAIL_PORT = 465 EMAIL_HOST_USER = config('MAIL_GUN_USERNAME') EMAIL_HOST_PASSWORD = config('MAIL_GUN_SMTP_PASSWORD') EMAIL_USE_TLS = True for MAIL_GUN_USERNAME I used my domains login for MAIL_GUN_SMTP_PASSWORD I used my domains password I tried all of mailguns different ports and switching between tls and ssl none of this worked. Any ideas what I'm doing wrong?