Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python urllib library giving an error in python 3+
I'm trying to create a shipment using the easyship API docs. I'm using python 3+ and I'm receiving this error " can't concat str to bytes ". I think this is probably because of the urllib library. How can I solve this error ? from urllib.request import Request, urlopen headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer xxxxxxxxxxxxxAPIKEYxxxxxxxxxx' } request = Request('https://api.easyship.com/shipment/v1/shipments', data=values, headers=headers) response_body = urlopen(request).read() print(response_body) -
Django How to save JSON data outside a view in a session and retrieve the saved data inside the view?
I have JSON data which I want to store uniquely for each user inside a session. The problem is, the module which generates the JSON data is async is outside the Django view because it is very resource demanding. I want the JSON data this separate module generates to be stored in a session so that the data is unique for each user. I have tried the following outside my view module: from django.contrib.sessions.backends.db import SessionStore s = SessionStore() s['json_data'] = json_var s.save() But when I try to read the saved session data back inside a view, it loads nothing e.g. it doesn't go inside if statement: if 'json_data' in request.session: json_var = request.session['json_data'] Is there an elegant way to do this? -
Django API returning a single object rather than my whole list when using Table.objects.filter(condition)
In my Django project I have two tables: User and Post, where each Post has a foreign key 'author' to a User. I want to display all the posts that belong to a single user, with the URL: .../users/<int:pk>/posts. I parse this into my view function with the header: def user_post_list(request, pk):, which to my knowledge gives my view function access to this int:pk variable. I define the posts I want to return using posts = Post.objects.filter(author=pk), which should give me a list of all the objects that have an 'author' attribute equal to int:pk. However, when I go to return these posts, rather than a list I get only one JSON object from the Post table with an 'id' attribute and 'author' attribute equal to int:pk Thanks -
how to submit the same forms in one page in django
i am struggling how to submit multiple the same forms in one page. i have 3 model classes: 1- Group_attribut 2- Attribute 3- Attribut_items i create this form : from django import forms from .models import Attribute, Attribute_Item class GroupAttrForm(forms.ModelForm): class Meta: model = Group_attribute fields = ('title', 'catId', 'slug', 'display_order',) class AttForm(forms.ModelForm): list = forms.ModelMultipleChoiceField( queryset=Attribute_Item.objects.all(), label='لیست ایتمها' ) class Meta: model = Attribute fields = ('title', 'type', 'slug', 'group_attributeId',) i want to use this form while creating Group_attribut - with on click save the group and its Attributes with their all Attribut_items- page is something like following link: http://uupload.ir/files/6vbl_attributes.jpg please help me -
how to pass data in dictionary in django
i want to pass the data from dictionary def add(request): if request.method == "POST": src=request.POST['src'] width=int(request.POST['width']) height=int(request.POST['height']) name=request.POST['name'] report_name ={'src':src, 'width':width, 'height':height, 'name':name} return render(request, 'report_one.html', {'report_name':report_name}) else: pass in above code if i pass whole dictionary report_name ={'src':src, 'width':width, 'height':height, 'name':name} in return like this ----- return render(request, 'report_one.html', {'src':src, 'width':width, 'height':height, 'name':name}) this will work and display the required page but if i pass report_name like this ---return render(request, 'report_one.html'{'report_name':report_name}) this will not work so my question is how to pass the dictionary from view to html templates in case of the data is taken by the other page -
error messages are not shown in django form
error messages are not working in Django templates. after add error code in html template it shows no error message in webapp when fields are empty and press on submit button. html5 error is "novalidate" in template. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django.contrib.auth.models import User from django.utils.translation import gettext,gettext_lazy as _ class SignUpForm(UserCreationForm): password1 = forms.CharField(label='Password',widget=forms.PasswordInput(attrs={'class':'form-control'})) password2 = forms.CharField(label='Confirm Password(again)',widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username','first_name','last_name','email'] labels = {'username':'Username','first_name':'First Name','last_name':'Last Name','email':'Email'} widgets = {'username':forms.TextInput(attrs={'class':'form-control'}), 'first_name':forms.TextInput(attrs={'class':'form-control'}), 'last_name':forms.TextInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}),} class LoginForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus':True, 'class':'form-control'})) password = forms.CharField(label=_('password'),strip=False, widget=forms.PasswordInput(attrs={'autocomplete':'current-password','class':'form-control'})) signup.html {% extends 'blog/base.html' %} {% load static %} {% block content %} <div class="col-sm-10"> <h3 class="text-white my-5">Signup Page</h3> <form action="" class="post" novalidate> {% csrf_token %} {% for fm in form %} <div class="form-group"> {{fm.label_tag}} {{fm}} {{fm.errors | striptags}} </div> {% endfor %} <input type="submit" value='Submit' class='btn btn-primary'> {% if form.non_field_errors %} {% for error in form.non_field_errors %} <p> {{error}} </p> {% endfor %} {% endif %} </form> </div> {% endblock content %} -
Use fullCalendar header only
I am using fullCalendar for my django project. For some of my template files(HTML files), I want to use only the header of the calendar not the calendar container. Can I use only the header of fullCalendar? if so how can I subtract container of the fullCalendar? Can anyone suggest me a better way to build a calendar header only? -
Django REST file upload results in different file size than original
When using Django REST Framework to handle file uploads using the FileUploadParser and storing the file on disk, is it normal for the final stored file (on the Django side) to have a different file size than the original file? I'm a newbie to Django (and Python in general) - my second week doing Django. I have a Python 3 script on a server (Ubuntu) that periodically uploads zip files to the Django (3.1) server using the Django REST Framework, also on Ubuntu. Using Python 3.8 on both sides. In each upload event, the file is always a single zip file (which only contains .txt and/or .csv files). The file upload is simple and is stored on disk on the Django side. From the sending side, I have experimented with a simple Python 3 script and curl as well, with differing results - the transferred files are always bigger than the original, and different between curl and my Python script. I am able to unzip and inspect the contents without issue; the text and csv files are identical in all cases. Needless to say, when I do a simple sftp, bypassing Django, the file size is identical - this is … -
Django - relation "app_name_modelname" does not exist
I've deployed my application to DigitalOcean. Everything works fine except this situation. I've added new GeneralComplaintDocument model, made migration locally, pulled from Github last version of project on DigitalOcean's server, deleted all migration files, migrated again, but still getting this error: relation "documents_app_generalcomplaintdocument" does not exist LINE 1: INSERT INTO "documents_app_generalcomplaintdocument" P.S: everything works fine on local server. -
Exception Value: 'NoneType' object has no attribute 'add', Categories name dont show up Django
Im trying to let user create a post and select a category, but when it selects a category and I post it, it gives me the error: Exception Value: 'NoneType' object has no attribute 'add'. If i go to my database, whatever I type, it is save except the category_id which is null. This is my code views.py: @login_required(login_url='login') def userposts_create_view(request): form= UserPostForm(request.POST or None) if form.is_valid(): data = form.cleaned_data categories = data.pop('categories', None) user_post = UserPost.objects.create(**data, user=request.user) if categories: user_post.categories.add(*categories) return HttpResponseRedirect("/posted/") context= {'form': form} return render(request, 'posts/userposts-create-view.html', context) #list view @login_required(login_url='login') def userposts_list_view(request): allposts= UserPost.objects.all() context= {'allposts': allposts, } return render(request, 'posts/userposts-list-view.html', context) #detail view @login_required(login_url='login') def userposts_detail_view(request, id=None): post= get_object_or_404(UserPost, id=id) context= {'post': post, } return render(request, 'posts/userposts-detail-view.html', context) I assume the error must be in the models but not sure... Models.py class Categories(models.Model): name = models.CharField(max_length=100, verbose_name='Nombre') User= settings.AUTH_USER_MODEL class UserPost(models.Model): user= models.ForeignKey(User, null=False, editable=False, verbose_name='Usuario', on_delete=models.CASCADE) title= models.CharField(max_length=500, null=False) content= models.TextField(null=False) categories = models.ForeignKey('Categories', null=True, blank=True, on_delete=models.CASCADE) public = models.BooleanField(verbose_name='Privada?',default=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name='Creado el ') updated_at = models.DateTimeField(auto_now=True, verbose_name='Actualizado el ') def save(self, *args, **kwargs): super(UserPost, self).save(*args, **kwargs) Forms.py from django import forms from .models import UserPost class UserPostForm(forms.ModelForm): class Meta: model= UserPost fields= … -
Django template add GET parameter after current URL
Previously, I handled my translation with GET parameter, by requesting the ?lang=<lang_code> on URL. <h6>{% trans "Translate" %}</h6> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <span id="language-icons"> {% for language in languages %} {% if language.code == 'id' %} <a href="?lang=id" title="Indonesia"> <img height="20px" src="{% static 'icons/flags/id.svg' %}"> </a> {% elif language.code == 'en' %} <a href="?lang=en" title="English"> <img height="20px" src="{% static 'icons/flags/us.svg' %}"> </a> {% endif %} {% endfor %} </span> When I handle with {{ request.META.QUERY_STRING }}, and the previous URL already included lang= param (like: /path/to/?page=2&lang=en). The next lang= will attempts multiple times (like: /path/to/?page=2&lang=en&lang=id). I want to replace the old lang=en param with new lang=id. So, the url should be /path/to/?page=2&lang=id. Here is what I was tried; {% with QUERY_STRING=request.META.QUERY_STRING %} {% if QUERY_STRING %} {% if 'lang' in QUERY_STRING %} <a href="?{{ QUERY_STRING|replace_with:"lang=id" }}"> <!-- something like `replacer` --> {% else %} <a href="?{{ QUERY_STRING }}?lang=id %}">...</a> {% endif %} {% else %} <a href="?lang=id">...</a> {% endif %} {% endwith %} I just think, the above problem maybe nice when handle with templatetags, like: @register.filter def cutoff_url(request, replacer='lang=id'): params = request.META.QUERY_STRING # 'id=1&lang=en' replacer_list = … -
How to delete a fk record in Django Rest Framework
My goal is to delete the fk record related with the record of the given id in the endpoint. my url path('car-pricing/<uuid:car_id>/', car_pricing), my model class Pricing(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) car = models.ForeignKey(Car, related_name="pricings", on_delete=models.CASCADE) In other words I want to delete a specific Pricing record given the id of a Car in my endpoint. By requesting with an id of a Car record I can get more than one Pricing records. Is it somehow possible to choose to delete a specific Pricing based on the id? my view(here, I do not know how to deal with delete function) elif request.method == 'DELETE': pricing_data = request.data return Response(status=status.HTTP_204_NO_CONTENT) Here the requested data is an empty QueryDict and it is ok, since there is no way to give requested data to a delete action in django rest framework -
How to serializer an ImageField from another model in django rest framework
I know there are many similar questions but none of them solves my problem. I have a simple topic that has an image field, a topic title, a topic content, a topic slug and etc. That topic is associated with a user using the foreignkey. The serializer is doing fine until the serializer for the image field was added. serializers.py class TopicDetailSerializer(serializers.ModelSerializer): topic_author = serializers.SerializerMethodField('get_topic_author') topic_author_picture = serializers.SerializerMethodField( 'get_topic_author_picture') class Meta: model = Topic fields = ['id', 'topic_title', 'topic_content', 'created_date', 'topic_slug', 'thread_title', 'topic_author', 'topic_author_picture', ] def get_topic_author_picture(self, topic): return topic.owner.profile_picture def get_topic_author(self, topic): return topic.owner.username The output in the console when I request the data from frontend: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte Ain't I just storing the path to the Image rather than the image itself? I mean I have a user profile serializer which sends information to the requested user and it includes an image. But it works fine. -
How to solve "OperationalError at / Could not decode to UTF-8 column 'mainpic' with text '����'"?
I saw some several similar questions, but I couldn't find the answer. This is the successful image without BLOB image files. It works fine when there aren't any images, but when I put images at my DB browser for SQLite, it doesn't work like below. The picture of adding some pictures through SQLite3 DB browser. This is the error code How can I solve this problem? Should I change encoding from utf-8 to another? from django.db import models class Restaurants(models.Model): name = models.CharField(max_length=100, blank=False, null=False) location = models.CharField(max_length=10, blank=False, null=False) xco = models.FloatField(max_length=20, default='') yco = models.FloatField(max_length=20, default='') upinfo = models.CharField(max_length=500, default='') downinfo = models.CharField(max_length=500, default='') resnumber = models.CharField(max_length=16, default='') mainpic = models.ImageField(blank=True, null=True) menupic = models.ImageField(blank=True, null=True) respic = models.ImageField(blank=True, null=True) This is the django framework part. -
"action" in form not redirecting to django views
Im new to django and new to stackoverflow too. Im trying to create my personal blog, but its comment section is not working. i tried and found that its url is continuously matching with my 'posts/str:slug' url and giving me the same page instead of executing the views. its doesnt even add comments when i checked my admin panel. but i can manually add comments to it and can display it. i think something is messed up with my URLS. Please help. **[blog/urls.py(app)]** from django.urls import path from blog import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('postComments', views.postComments, name="postComments"), path('', views.home, name='home'), path('blog/', views.blog, name='blog'), path('contact/', views.contact, name='contact'), path('search/', views.search, name='search'), path('login', views.login, name='login'), path('logout/', views.logout, name='logout'), path('error', views.error, name='error'), path('posts/<str:slug>', views.posts, name='posts'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) **[main urls.py]** from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static admin.site.site_header = "BlueBlog Administration" admin.site.site_title = "BlueBlog Admin Panel" admin.site.index_title = "Welcome to BlueBlog Admin Panel" urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('blog.urls')), path('register/', include('register.urls')), path('error/', include('blog.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) **[views.py] here postComment is the view i am not redirecting to** … -
How to count values of many field for one object in Django?
Actually I'm stack in one thing. I'm learing a lot but I need your help... Django Models from django.db import models # Create your models here. class Car(models.Model): mark = models.CharField(max_length=180) model = models.CharField(max_length=180, unique=True) def __str__(self): return "Car mark : {} Car model {}".format(self.id,self.model) class Rate(models.Model): class Ratings(models.IntegerChoices): One = 1 Two = 2 Three = 3 Four = 4 Five = 5 grade = models.IntegerField(choices=Ratings.choices) car = models.ForeignKey(Car, on_delete=models.CASCADE,blank=True, null=True, related_name='rates') First of all - I would like to get avg value of rates assigned to one object. Secondly, I would like to count how many rates each object has. -
why I am not able to makemigrations to postgres DB?
My current Django project is binded to default SQLite DB. Now going forward I wanted to migrate to postgres. I have followed this link There's nothing wrong with the installation of the Postgres. I have followed exactly the same steps mentioned in the website: Login with the "postgres" user. sudo -u postgres psql Create a Database. CREATE DATABASE myproject; Create user and assign password. CREATE USER myprojectuser WITH PASSWORD 'password'; Grant privileges to the user. GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser; After this I added the below properties to my Django's settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DB_name', 'USER': 'new_User_name', 'PASSWORD': 'new_user_password', 'HOST': '', 'PORT': '', } } Now, when I do python manage.py makemigrations I get invalid password error. Going forward, when I execute some postgres commands to check the environment. I have below observation. In the Postgres shell, I execute '\l' to see the databases. I see below. Name | Owner | Encoding | Collate | Ctype | Access privileges -------------------------+----------+----------+---------+---------+-------------------------------- DB_Name | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =Tc/postgres + | | | | | postgres=CTc/postgres + | | | | | new_User_name=CTc/postgres Then I execute '\du' to see the … -
The record is not saved in the DJango-SQLite database
I am trying to save a record in the database of a model (Score) that is related to two other models (User and Exercise), I receive the form correctly or so I think, and using the save() instruction does nothing. I don't even get errors. Here the code: forms.py class ScoreForm(forms.ModelForm): #idUser = forms.IntegerField(widget=forms.HiddenInput(), label='idUser') idExercise = forms.IntegerField(widget=forms.HiddenInput(), label='idExercise') value = forms.FloatField(widget=forms.HiddenInput(), label='Value') class Meta: model = Score fields = ['idExercise', 'value'] views.py def save_exercise(request): if request.method == 'POST' and request.is_ajax: form_score = ScoreForm(request.POST, instance=request.user) if form_score.is_valid(): form_score.save() else: print('Tenemos un error') return HttpResponse('Respuesta') JavaScript document.getElementById('id_value').value = score; document.getElementById('id_idExercise').value = idexer // document.getElementById('id_idUser').value = iduser let data = new FormData($('#scores').get(0)); Swal.fire({ title: '<strong>Tu resultado: </strong>', icon: 'success', html: `<div class="progress" style="height: 30px;"><div class="progress-bar progress-bar-striped progress-bar-animated" style="width:${number}%">${number}%</div></div>` + `Ganaste: ${score.toFixed(2)}`, focusConfirm: false, confirmButtonText: '<i class="fa fa-thumbs-up"></i> Okey!', preConfirm: () => { $.ajax({ type: "POST", url: "/polls/save/", data: data, processData: false, contentType: false, success: function(){ console.log('Funciona!') show_exercise() } }) } }) In html file <div class="row d-flex justify-content-center"> <form method="POST" action="" novalidate id='scores'> {% csrf_token %} {{ form|crispy}} </form> </div> All the inputs of the form are type hidden since after a couple of calculations I assign their respective values, the form … -
Passing parameters to template for NavBar menu in Django
I am trying to switch my head to start using MVC. I have a Base HTML template, with an include NavBar code: {% include "navBar.html" %} So far, so good. Now, I want to send information to it (to the navBar.html template) regarding the Menu buttons. I have some simple buttons, and others with drop-button behavior. My buttons are objects, they have information about name, href, position, etc, type (simple-button or drop-button) So, I created a nested list in this way: outer_list = [] for a in UserModule.objects.filter(user=user_id, is_active=True): inner_list = [] inner_list.append(UserModule(a)) for b in Submodule.objects.filter(module=a.module, is_active=True): inner_list.append(Submodule(b)) outer_list.append(inner_list) return {'outer_list': outer_list} So, my first element in every inner_list is the head of the possible drop-button, or a simple drop-button depending on his type attribute. The list is like at the end is like this: [0] Button-Simple-A [1] Button-Drop-A => [sub-button-1, sub-button-2, sub-button-3] [2] Button-Simple-B and so on. When I pass this outer_list to the template, the thing I have to do to arrange the buttons into the menu are crazy things. It has no sense to use MVC if I am going to write a lot of code in the template. Until now, I am doing this over … -
How to get the Django csrf token in a Vue js application
How do i get the csrftoken in Vue js application running on port 8080 from a Django application running on port 8000. From the docs i got know about the ensure csrftoken decorator and the getCookie function. But all this works when i do not seperate the front-end and the back-end. I want to use axios to transfer data between the Django and Vue app -
Django forms - FK QuerySet manipulation
I have a FK field and want to restrict the QuerySet. class KimEditForm(forms.ModelForm): class Meta: model= Kim fields = '__all__' exclude = ['order','customer','order_date', 'start_date'] def __init__(self, *args, **kwargs): kim = [veh.vehicle for veh in Kim.objects.filter(order_status = 'Active')] vehicle = [item for item in Vehicle.objects.filter(vehicle_status = 'KIM') if item not in kim] super(KimEditForm, self).__init__(*args, **kwargs) self.fields['vehicle'].queryset = vehicle what is wrong with my code I get a error. 'list' object has no attribute 'all'. -
Losing user input data due to heroku databse refresh (django backend)
So I made a django app and deployed it using Heroku - with s3 for file uploads and whitenoise for static files. So I use the admin page to add updates to the displayed sections, like new blog entries (for example or comments). The problem is that any database update using the admin page stays for a day at most and then refreshes, going back to the previous state and making me lose all the new data. I have tried some stuff, but I am totally out of my depth here. I even tried pulling the changes made back into my local copy and pushing again to repository but it shows no changes. Is it something to do with how Django takes in user input? If anyone could help me that would be amazing. If you guys need any code please tell me. -
I want to give some token to Anonymous User and store his data, if the user is registered back end should transfer the data
the 'token' is generated on back end as above def get(self, request): if self.user.is_authenticated: # the logged user's data is stored else: token = get_random_string() #this function was imported from other file here I am sending the token to requested url as Json file but can't take it on front end and send it to back end when the user is requested to the url before the user already requested! please help me out!!! here is the Vue file in front end searchProduct(keyword){ if(this.selectedCatId != '' && this.selectedCatId != 'all'){ this.$router.push({name: 'search', query:{ k:keyword, cpn: this.$route.query.cpn ? this.$route.query.cpn : 1, cid: this.selectedCatId} }) }else{ this.$router.push({name: 'search', query:{ k: keyword, cpn: this.$route.query.cpn ? this.$route.query.cpn : 1} }) } this.$axios.get('requested url'+this.searchKeyword+'&pagenum=1&productsPerPage=10', { params: { usertoken: localStorage.getItem('unregUserSearchToken') } }) .then(function (response) { localStorage.setItem('unregUserSearchToken', response.data.search_token) console.log(response); }) -
Can not solve Git error "refusing to merge unrelated histories"
When I tried to pull git pull https://myid@bitbucket.org/myid/abc.git error occurred branch HEAD -> FETCH_HEAD fatal: refusing to merge unrelated histories Then I tried this git pull origin master --allow-unrelated-histories error occurred fatal: 'origin' does not appear to be a git repository fatal: Could not read from remote repository. Then I tried this git mergetool error occurred This message is displayed because 'merge.tool' is not configured. See 'git mergetool --tool-help' or 'git help config' for more details. 'git mergetool' will now attempt to use one of the following tools: tortoisemerge emerge vimdiff No files need merging Check branch name git branch --contains=HEAD branch is only master master I can not figure out how to fix this problem, please teach me what I can do next?? -
Syntax Error when migrating a django server
I am trying to make a django server for a sociometric badge (https://github.com/HumanDynamics/openbadge-server) for our university's project. The code (and the whole badge) has been done by someone else and I have not myself changed anything. I am able to build the server but when trying to migrate or create a superuser, I get a syntax error. I've been trying to troubleshoot it by myself but I have very limited knowledge of python, django and Ubuntu so I'm probably missing something. I tried asking the original developer but he is busy with other stuff so haven't gotten a reply but as I have to get the project going, I'll try asking here. The error implies an error in the line 44 of /usr/local/lib/python2.7/site-packages/pkgconf/init.py but I cannot find the file so I cannot check it. In fact, the whole site-packages folder is empty so I wonder if I have installed modules in a wrong way? The code is written in python2.7 so I also wonder if the python2.7 being EOL could cause issues? It has already broken some parts, mainly how to get some of the modules. The code used in this project can be found here: https://github.com/HumanDynamics/openbadge-server Also the main …