Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku push fails because it can't find module allauth
I am trying to push a Django app to to Heroku. I get the following error on trying to push to heroku remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: -----> Installing python-3.7.10 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing dependencies with Pipenv 2020.11.15 remote: Installing dependencies from Pipfile.lock (a6086c)... remote: -----> Installing SQLite3 remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 983, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'allauth' … -
DRF error create() got multiple values for keyword argument 'hnid'
so I am building a pet blog project where my scenario is - my users will be able to post multiple images and audios if they want while doing so , am facing several problems - while trying to post through POSTMAN . I am getting an error saying create() got multiple values for keyword argument 'hnid' .. while querying using UUID , it is throwing , a String naming "HNUsers object (e3ec1a43-ebc4-47b9-bf2f-55967af8ea71)" where I just wanted UUID(e3ec1a43-ebc4-47b9-bf2f-55967af8ea71) but came with extra HNUsers object Here is my Profile model class HNUsers(models.Model): USERTYPE = ( (u'RU', u'REGULAR USER'), (u'HN', u'HN'), ) GENDER = ( (u'M', u'Male'), (u'F', u'Female'), (u'O', u'Other'), ) ip_address = models.CharField("IP Address" , max_length=100, blank=True, null=True) full_name = models.CharField("Full Name", max_length=100, null=True, blank=True) username = models.CharField("Username", max_length=100, null=True, blank=True) email = models.EmailField("Email", blank=True, null=True) user_type = models.CharField("User Type", max_length=2, choices=USERTYPE, null=True, blank=True, default=USERTYPE[0][0]) mobile_number = models.CharField("Mobile Number", max_length=20, blank=True, null=True) date_of_birth = models.DateField("Date of Birth", auto_now_add=False, blank=False, null=True) gender = models.CharField("Gender", max_length=1, choices=GENDER, blank=True, null=True, ) registration_date = models.DateTimeField("Registration Date", auto_now_add=True, null=True, blank=True) city = models.CharField("City", max_length=50, blank=True, null=True) country = models.CharField("Country", max_length=50, blank=True, null=True) profile_img = models.ImageField("Profile Image", blank=True, null=True) first_img = models.FileField("First Image", blank=True, null=True) first_img_url … -
Creating a ContentVersion in Salesforce from Django Application
I have some InMemoryUploadedFiles that users uploaded to my Django application. I need to pass these files' data encoded with base 64 as the VersionData when creating a ContentVersion object in Salesforce. If I pass in sample data such as fileData = base64.b64encode(b"testing"), everything works. The problem is trying to read/encode the data from Django's InMemoryUploadedFile If I pass in base64.b64encode(files[file].file.read()) as the VersionData (files[file] is the InMemoryUploadedFile - I'm looping through each one), it gives me the "bytes object is not JSON serializable" error. If I pass in the string version of that: str(base64.b64encode(files[file].file.read()), then the file gets uploaded but the contents are gibberish (aka a string of bytes). How do I format my InMemoryUploadedFile in such a way that I can pass the file's contents to the REST API call properly? More full code if it helps: def postFilesToDB(self, docRecords, files): payloadDict = {'passport_picture': { "name":"Passport Picture", "path":"", "data": None}, 'teudat_oleh': { "name":" Teudat Oleh", "path":"", "data": None }, 'tzav_giyus': { "name":"Tzav Giyus", "path":"", "data": None }, 'teudat_boded': { "name":"Teudat Boded", "path":"", "data": None }, } docTypeToPayloadEntry = { 'Passport Photo Scan': 'passport_picture', 'Teudat Oleh/Zakaut': 'teudat_oleh', 'Teudat Oleh/Zakaut - LSP Countries': 'teudat_oleh', 'Tzav Giyus': 'tzav_giyus', 'Teudat Boded': 'teudat_boded' … -
Separate documentations for internal and external APIs (drf_yasg)
I have two set of APIs: Internals, which are used in our client applications which we develop in our team, And externals, which is used by our business partners. I want to have a single document page which by authentication, shows internals APIs to our developers, and external APIs to every other viewer. How can I do that? I use: Django, DRF, and drf-yasg. P.S: I know this question is very general, but I do not have any clue where to start. I only guess some settings in get_schema_view, my views, and URL patterns are needed. -
Django - How turn string to link in template?
There is a model with name and link to their profile: from django.db import models class Person(models.Model): name = models.CharField(max_length=30) link = models.CharField(max_length=500) The table has the below values: name: Alex Link: www.example.com/alex name: Jo Link: www.example.com/jo In template I would like to get the hyperlink to the profiles. I tried the below, but got wrong link: <!DOCTYPE html> <html> <head> <title>Person</title> </head> <body> Name: {{ name }}, <a href="{{ link }}">Profile</a> </body> </html> It gives the link but the string is added to the end of the website address like this: http://www.website.com/person/www.example.com/jo How is it possible to fix this issue? -
Heroku Django install pillow
I have a problem with Heroku and Pillow i developed a apps with django and i have a columns with ImageField During the deploiement in heroku, i have a error message for pillow install with pip. error message: product.Profile.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Model django: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(null=True) Do you have a solution to my problem? Thank you -
Manage ListView and CreateView on the same template: how to submit data and update listView without reloading the page?
I want user to be able to add new record form a page and the list of records, that would be on the same page above, be updated without reloading the page (see attached picture below) For now, solutions I've read are to pass queryset (to display the list of records) in the context of createview But this way, user will submit, and page reloaded, for each new records... As User may have to enter hundreds of records, it is not a satisfactory solution so, maybe I should use Ajax to post new records and update the list of records But I wonder if Django has an in-a-box solution to resolve this problem? -
axios HTTP POST returns 400 undefined
I send data to an api with axios : function send_prefered_times_to_time_api(data){ axios({ method: 'post', url: 'https://modules.myadmin.com/api/time/calculate/', data: data, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).catch((error) => console.log( error.response.request._response ) ); console.log("data:",data); } but i get this error: POST https://modules.myadmin.com/api/time/calculate/ 400 undefined -
How to traverse multiple models properly in my queryset?
These are my models for the roles management(please suggest if you have better idea for this modeling). The problem here I get is while filtering only the menus which are assigned for the users. currently all the menus listed for the logged in user. What I want is list only menus if user has either create, update, delete, view status True. How can I do this ? The process of role assignment is. create role with some name(e.g Admin) assign users to the role assign menus and menu rights(create.update..) to the role. At login of user, if user is assigned to any role then I want to display that role's all menus if any create,update status is True. The current response "data": [ { "name": "Menu1", "code": "01", "can_update": true, "can_view": true, "can_delete": false, "can_approve": false, "can_create": true }, { "name": "Menu2", "code": "02", "can_update": false, "can_view": false, "can_delete": false, "can_approve": false, "can_create": false }, { "name": "Menu3", "code": "03", "can_update": false, "can_view": false, "can_delete": false, "can_approve": false, "can_create": false } ] } The response I want is: "data": [ { "name": "Menu1", "code": "01", "can_update": true, "can_view": true, "can_delete": false, "can_approve": false, "can_create": true }, ] } I want … -
How to add custom view page to django admin?
I have a parent-child models. It's kind of a coctail recipe, but it's about fish foods. I want to give a recipe calculator for each recipe. My current approach simply just add a link column at the list-view here is a snip of my admin.py class BahanCampuranAdmin(admin.ModelAdmin): list_display = ('name','_isfood', '_vubuy','_pbuy','userv','uconv','_bikin') fields = ('isfood','name', 'ubuy', 'vbuy','userv','uconv') readonly_fields = ['pbuy'] inlines = [ KomponenCampuranAdmin, ] def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(user=request.user) def _bikin(self,obj): if obj.ingridient.exists() : link="<a href='/catatkolam/recipecalc/{0}'>bikin</a>" return format_html(link, obj.id) return '-' _bikin.allow_tags=True _bikin.short_description='Bkin' ... This is what I got when clicking the link at the rightmost column. Look that it throw the user out of 'admin site' Here is my current template. {% extends "admin/base.html" %} {% block content %} <style> .Recipe-IngredientList { width: 250px; border: 1px solid #777; border-radius: 3px; padding: 5px; margin-top: 5px; } .Recipe-Ingredient { border-bottom: 1px solid black; padding: 5px 0; } .Recipe-Ingredient:last-child { border-bottom: none; } .Recipe-Ingredient span { font-weight: 600; } </style> <script> window.console = window.console || function(t) {}; </script> <script> if (document.location.search.match(/type=embed/gi)) { window.parent.postMessage("resize", "*"); } </script> <div> <label for="serving"> <h3>{{name}}</h3> <input type="number" id="servingInput" value={{vbuy}}> <span STYLE="font-weight:bold">{{ubuy}}</span> </label> <div class="Recipe-IngredientList"> {%for k in komponen%} <div class="Recipe-Ingredient js-recipeIngredient" data-baseValue={{k.qty}}>{{k.name}} : <span></span> … -
MariaDB replacing MySQL in Django
I have a project that was built using MySQL 5.4. But now I witched to MariaDB 10.3. If I understand correctly, the pip package mysqlclient==1.4.6 should still work on the new Database. Indeed, almost everythings works without problems with MariaDB on the webserver. However, I'd like to use MariaDB in my developement environment aswell. I'm using WAMP for the MySQL DB. In the phpMyAdmin landing page, I have to choose between MySQL and MariaDB databases. How can I tell Django to go to the MariaDB section? If I ignore that and just run manage.py check, I get the following errors: MySQLdb._exceptions.OperationalError: (1049, "Unknown database 'sampleDBmariaDB'") ... ... django.db.utils.OperationalError: (1049, "Unknown database 'sampleDBmariaDB'") -
New model field is not showing in admin page on PythonAnywhere
I have a problem when adding a new field to my models.py in PythonAnywhere. My models.py looks like the following, and I recently added the description field to it. class Post(models.Model): title = models.CharField(max_length=40, unique=True) cover = models.ImageField(upload_to='images/') description = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') slug = models.SlugField(null=False, unique=True) def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) updated_on = models.DateTimeField(auto_now= True) shortcontent = models.CharField(max_length=150) content = RichTextUploadingField(blank=True) created_on = models.DateTimeField(auto_now_add=True) language = models.IntegerField(choices=LANGUAGE, default=0) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title I did run the makemigrations and python manage.py migrate commands, but the description field is not showing on my admin page: My admin.py looks like this: class PostAdmin(admin.ModelAdmin): list_display = ('title', 'status','created_on') list_filter = ("status",) search_fields = ['title', 'content', 'description'] prepopulated_fields = {'slug': ('title',)} class Media: js = ('ckeditor.js',) # do not write '/static/ckeditor.js' as Django automatically looks # in the static folder admin.site.register(Post, PostAdmin) What can I do to make sure the description field shows up on my admin page. I am using Python 3.8 in Pythonanywhere. -
Looking to modify host file in MacOs
I am following a tutorial on multi-tenancy in Django (10:58/11:42) and I would like to modify the hosts file which I located alreadty. When I try to add a single letter, I get rejected: But this leaves me quite confused, this is my laptop, and I do not have permission? Is there a way to do this differently ? -
You are trying to add a non-nullable field '_response_rendered'; django-markupfield
Upon wanting to add some Markdown to a project, I've decided to install django-markupfield to serve this objective. The only thing is that I've installed my models and associated fields ahead of making this decision; now replacing a TextField with MarkupField. When attempting to make a migration to adjust for this, the following is brought up: You are trying to add a non-nullable field '_response_rendered' to answer without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py What would be an appropriate default value to add to the fields that will be prompting for such? I have never been too sure of this question in general when it comes to using Django as well, so clarification would be appreciated. https://github.com/jamesturk/django-markupfield class Question(models.Model): title = models.CharField(max_length=50) body = MarkupField( markup_type="markdown", escape_html=True ) dated = models.DateField(default=date.today) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() status = QuestionStatusQuerySet.as_manager() class Meta: ordering = ['-dated'] … -
how to run Django locally as a windows executable app
I'm considering building app with Django for only one user that would run application locally on windows. I read about containerizing Django apps, but it's new for me. My goal is to run Django server on one click like a standard windows app and connect to it on localhost and interact with web browser. It is even possible? -
Data from request.POST are not being used to fill django form in views
I'm new in a Django and I try to exercise in easy project. My problem is that when I try to save the data from request.POST to ListForm it doesn't work. In the request.POST object I can find only a csrf_token. Can you help me,how to fix it? vievs: def home(request): if request.method=='POST': a=request.POST form =ListForm(request.POST) list_items = List.objects.all if form.is_valid(): form.save() list_items=List.objects.all #messages.success(request,('Udało się dodać')) return render(request,'home.html' ,{'list_items':list_items,'ok':'ok','a':a}) else: list_items = List.objects.all return render(request, 'home.html', {'list_items': list_items,'nie_ok':'nie_ok'}) form in html: <form class="d-flex" action="{% url 'home' %}" method="post"> {% csrf_token %} <input class="form-control me-2" type="search" id='teraz'placeholder="your new task" aria-label="Search"> <button type="submit" class="btn btn-outline-secondary" name="item">Add to list</button> </form> request.POST object: <QueryDict: {'csrfmiddlewaretoken': ['jCBOIk4mLr96d6ffPUDiLdJ01oVsw5eAATzeJqlQrC0H4TYTAP8OqnQFHrFZgOeo'], 'item': ['']}> models: class List(models.Model): item=models.CharField(max_length=50) completed=models.BooleanField(default=False) def __str__(self): return self.item forms: class ListForm (forms.ModelForm): class Meta: model =List fields=['item','completed'] -
I want to mention group the user either admin or customer while register(programmatically) in Django. I am new to Django
From the admin panel I can group the user either customer or admin. How do to programmatically? This my function register in views.py. @unauthenticated_user def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() profile = form.save(commit=False) profile.save() user = form.cleaned_data.get('username') us1 = User.objects.filter(username=user).first() us1.is_staff = True us1.is_superuser = False us1.save() messages.success(request, 'Account was created for ' + user) return redirect('loginpage') context = {'form':form} return render(request, 'register.html', context) -
Django changes datetime automatically
I have django project and one separate service. In django timezone is UTC+3 and in separate service I have written pure sql codes like below INSERT INTO Table(something,something,datetime) VALUES(%s,%s,%s) as a datetime field if I send 2021-04-28 01:00:00, django will save it 2021-04-28 04:00:00, 3 hours more. How can I implement db to store exactly what I send there. -
Permission error while access the sqlite3 with basic Django apps
I'm trying to follow the tutorial, but facing the below error. The error was disappeared when I changed the permissions of the parent folder and the db.sqlite3 file to 777, but that's not the good idea. What's the alternative? Reference: https://docs.djangoproject.com/en/3.2/intro/tutorial02/ Error: OperationalError at /admin/logout/ attempt to write a readonly database Request Method: GET Request URL: http://x.x.x.x/admin/logout/ Django Version: 3.1.6 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: /opt/bitnami/python/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute Python Executable: /usr/bin/python3 Python Version: 3.8.7 Python Path: ['/opt/bitnami/python/lib/python38.zip', '/opt/bitnami/python/lib/python3.8', '/opt/bitnami/python/lib/python3.8/lib-dynload', '/opt/bitnami/python/lib/python3.8/site-packages', '/opt/bitnami/python/lib/python3.8/site-packages/setuptools-46.4.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/pip-20.3.4-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/virtualenv-20.4.2-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/six-1.15.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/filelock-3.0.12-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/distlib-0.3.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/appdirs-1.4.4-py3.8.egg', '/opt/bitnami/apps/django/django_projects/tutorial'] Server time: Thu, 29 Apr 2021 06:17:14 +0000 Folder and file status: bitnami@ip---:/opt/bitnami/apps/django/django_projects$ ls -al total 12 drwxrwxr-x 3 root root 4096 Apr 22 05:09 . drwxr-xr-x 3 root root 4096 Apr 22 05:09 .. drwxrwxr-x 6 www-data www-data 4096 Apr 29 06:16 tutorial bitnami@ip---:/opt/bitnami/apps/django/django_projects$ ls -al tutorial/ total 168 drwxrwxr-x 6 www-data www-data 4096 Apr 29 06:16 . drwxrwxr-x 3 root root 4096 Apr 22 05:09 .. drwxr-xr-x 2 www-data www-data 4096 Apr 22 05:45 conf -rwxrwxrwx 1 www-data www-data 143360 Apr 29 06:16 db.sqlite3 drwxr-xr-x 4 www-data www-data 4096 Apr 28 16:08 hello_world -rwxr-xr-x 1 www-data www-data 664 Apr 22 … -
Django how to retrieve values from a database for an existing post so that we can edit
I am displaying a form for a posting which has already been saved to the database. I am giving the user the option to view the values as they are in the database and give him the option to edit them. However, it is not working for radio button and dropdown. I have tried writing something but it does not display the correct values. Here is the code snippet: <div class="form-row"> <div class="form-group col-md-6"> <label>Internship Type</label> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="customRadioInLine1" name="internship_mode" class="custom-control-input" value="Office"> <label class="custom-control-label" for="customRadioInLine1">Office</label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="customRadioInLine2" name="internship_mode" class="custom-control-input" value="Work From Home"> <label class="custom-control-label" for="customRadioInLine2">Work From Home</label> </div> </div> <div class="form-group col-md-6"> <label for="industry_type">Industry Type</label> <select class="form-control" id="industry_type" name="industry_type" selected=" {{ internship.industry_type }}"> {% for ind_type in industry_types %} <option value="{{ ind_type }}" {% if '{{ ind_type }}' == '{{ internship.industry_type }}' %}selected="selected" {% endif %}> {{ind_type}}</option> {% endfor %} </select> </div> -
Display the students named John Doe per class section using array
This is my example data. Those data are insurance claims and numbers in claims represents the number of claims per insurance category. What I was trying to do is { "Month": [ "April", "February", "March" ], "Claim(s)": { "": 18, "Energy": 1, "\"health\"": 5, "health": 38, "Credit": 7, "Bank Transfer": 5, "CAR": 1, "home": 5 } What I was trying to do is: Months: [Jan, Feb, March, Apr, May, Jun, July, Aug, Sept, Oct, Nov, Dec] Health: [0, 29, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Car: [0,1,0,0,0,0,0,0,0,0,0,0] Those element values represents that there were 29 health claims, and 1 car claim on month of February 2021. My code for the first data: class GetClaimsCompare_year(APIView): def get_claim_count(self, claims_data, claim_type): claims_count = claims_data.filter(claim_type = claim_type).count() return claims_count def get_claims_type(self, claim_per_month): return claim_per_month.claim_type def get(self, request): today = datetime.now() claims_data = Claims.objects.filter(modified_at__year =today.year) claim_per_month = claims_data.annotate(month = TruncMonth('modified_at')).values('month').annotate(claim_type=Count('id')) labels = [] claims_type = list(set(map(self.get_claims_type, claims_data))) final = {} for claims in claim_per_month: month_label = claims['month'].strftime('%B') labels.append(month_label) #labels.append(claims['month']) for claim_type in claims_type: final[claim_type] = self.get_claim_count(claims_data, claim_type) context = { 'Month':labels, 'Claim(s)':final } return Response(context) -
Python Django- How do I interact/handle an uploaded text file
I have python code that reads in a document and parses it through into key words. I'm new to Django, but I have a working project that the user uploads a document and that file is saved to a postgres database. I'm having a really hard time figuring out how combine this project with the python code; I don't understand how to take that upload file and and break it down into words. **What I'm desperate to understand:**is how a python script is added and applied in Django; and then take the returned output, pieces of the broken down text, can be stored under columns in a Postgres db. Similar to how a python code can read in a text file and split up it up into words and organize the words into columns in a pandas DB. I'm struggling a lot with applying this function in a django context. I'm not sure if it would be easier to apply a python script to the UploadFile.object or apply the python functions after form is validated. I'm having a hard time finding an explicit example of this. I would greatly appreciate if anyone could shed some light on this! code: import … -
Google Chrome limits borders of a page with blue dotted lines
Now I'm working on my pet project of a blog using Django. When I run the server in Google Chrome, it shows these blue dotted lines on a page, thus displacing all elements. At the same time, when I access the same site on Microsoft Edge, everything looks okay. What is the problem with this page in Chrome? The page looks like this in Chrome: Chrome And like this in Edge: Edge -
is there elif syntax error please find the error?
def mobile(request, data=None): if data == None: mobiles = Product.objects.filter(category='M') elif data == 'Redmi' or data == 'Samsung': mobiles = product.objects.filter(category='M').filter(brand=data) return render(request, 'app/mobile.html', {'mobiles': mobiles}) -
How to group by list of values in django
I'm trying to get api params: ?group_by=student,year, I get it in my endpoint like this: group_by_items = self.request.query_params.get('group_by') the result is a string that I need to pass it to the values method, so this is how I did it: group_by_items = group_by_items.split(',') res = res.values(group_by_items).annotate(presence=Sum('presence')) res is the queryset. after running this code I get this error: TypeError: unhashable type: 'list' How can I resolve this? Thank you.