Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set django url using jquery
How can I set url with params in django temple from jquery ? My template.html <div id="buynow"> <div> <a id="myLink" href="" class="btn btn-outline-secondary">Buy now</a> </div> </div> My jquery.js var fee = "200"; var total = "1000"; $('#buynow').click(function(){ $('#myLink').prop('href', '/payment/'+parseInt(getAmounts)+'/'+parseInt(totals)+'/'); }); My urls.py urlpatterns = [ path('payment/<int:fee>/<int:total>/', views.payment, name='payment'), ] -
Python django project unable to use .scss files in my project
I am using pre built template in python django project it has .css and .scss files . I am not able to style the project and use use .scss file in my project -
The current path, didn’t match any of these
Hi I am new to django and I have been making a CRUD project,while pressing the 'EDIT' button the below error comes heres the code in views.py def edit_cat(request,id): if request.method == 'GET': print('GET',id) editcategory = Categories.objects.filter(id=id).first() s= CategoriesSerializer(editcategory) return render(request,'edit_cat.html',{"Categories":s.data}) else: print('POST',id) editcategory = {} d = Categories.objects.filter(id=id).first() if d: editcategory['name']=request.POST.get('name') editcategory['description']=request.POST.get('description') print(editcategory) # Updateemp = EmpModel.objects.get(id=id) #print(Updateemp) form = CategoriesSerializer(d,data=editcategory) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('categories:show_cat') else: print(form.errors) urls.py from django.urls import path from categories import views from django.urls.conf import include from django.conf import settings from django.conf.urls.static import static urlpatterns=[ path('',views.show_cat,name="show_cat"), path('insert_cat/',views.insert_cat,name="insert_cat"), path('edit_cat/<int:id>/',views.edit_cat,name="edit_cat"), path('del_cat/',views.del_cat,name="del_cat") ] is there a silly mistake I have made in the codes? please help -
How to call Dajngo render view from another APP render view template
I have two apps with one render view in each. First view. This selector HTML have the drop-down boxes with the options for the user to choose nothing else than this. def selectionView(request, *args, **kwargs): return render(request, 'selector.html') Second view def dataView(request, *args, **kwargs): //code here to look into the database and then use the data in the HTML. //The filter will be taken from the dropdown box created in the above //selector.HTML FILE. return render(request,'tableContent.html', {'users': users}) My question here is there any way I can call the data view with values of dropdown box passed using JQuey or javascript or python from the first view. What I am looking for? Use the selection view as a landing page with the drop-down options and then use that dropdown option to call the data view and show the results. The records received are in thousands. Question? Is there any way I can do this like calling the render view from the HTML template of other Django view and passing the dropdown values as parameters to the view I want to call -
Running django tests in github actions causes Error code 137
I have an app made up of multiple containers that I run with docker-compose. I've tried adding a .yml file to my .github/workflows folder in order to run unit tests on every push to the repo. The containers start up fine but when it comes to the step for running the tests, there is an error: Error: Process completed with exit code 137. After looking up that exit code online, I found that this is a memory error but I can't figure out what is causing it and how to fix it. Here is my .yml file for running the tests. name: django-tests on: push: branches: [develop] jobs: start_docker: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Create env file run: | touch .env echo POSTGRES_ENGINE=${{ secrets.POSTGRES_ENGINE }} >> .env echo POSTGRES_DATABASE=${{ secrets.POSTGRES_DATABASE }} >> .env echo POSTGRES_USER=${{ secrets.POSTGRES_USER }} >> .env echo POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }} >> .env echo POSTGRES_HOST=${{ secrets.POSTGRES_HOST }} >> .env echo POSTGRES_PORT=${{ secrets.POSTGRES_PORT }} >> .env echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env cat .env mv .env project/db - name: Start containers run: docker-compose -f "docker-compose.yml" up -d --build - name: Run tests run: docker exec my_app python manage.py test - name: Stop containers run: docker-compose -f … -
Django - importing data from an external file
I have a question: I have a code in views that does the same thing (displays 2 arrays) only in an external file I have it done a little better and I would like to display this data from an external file. How to do it? Thx for your help. views. def calculate(request): ... elif request.GET.get('Automatic'): ans1 = ([x for x in range(0, 100, 1)]) # X ans2 = ([(randint(1, 100) * y) for y in range(0, 100, 1)]) # Y ans = np.concatenate([ans1, ans2]) calculate.py from random import randint import time t = time.time() class Calc: def __init__(self): pass def position(self): self.positionX = [] self.positionY = [] self.positionX.append([(randint(1, 100) * x) for x in range(1, 2, 1)]) self.positionY.append([(randint(1, 100) * y) for y in range(1, 2, 1)]) return self.positionX, self.positionY def __str__(self): return {self.positionX, self.positionY} if __name__ == '__main__': t = 0 while t < 20: hear = Calc() print('X: ', hear.position()[0], 'Y: ', hear.position()[1]) time.sleep(0.4) t += 1 template: !DOCTYPE html> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/light.css"> <title>{% block title %}{% endblock %} </title> </head> <div class="container container-fluid text-center "> <h1>Answer is</h1> {# <h3>{{answer}}</h3>#} {% for answers in answer %} {{ answers }} {% endfor %} <br> <br> <button … -
form is not valid but Django didn`t return any error
there is two attribute 'name' and 'slug' as you can see in code I send wrong data to 'slug' and 'name' is empty but validation didn`t work. Models class Tag (models.Model): name = models.CharField(max_length=50, db_index=True) slug = models.SlugField(unique=True, help_text='a label for url config') class Meta: ordering = ['name'] def __str__(self): return self.name.title() def get_absolute_url(self): return reverse('organizer:tag_detail', kwargs={'slug': self.slug}) forms class TagForm (forms.Form): class Meta: model = Tag fields = '--all--' def clean_name (self): return self.cleaned_data['name'].lower() def clean_slug (self): new_slug = (self.cleaned_data['slug'].lower()) if new_slug == 'create': raise ValidationError('slug may not be "create".') else: return new_slug shell In [11]: from organizer.forms import TagForm In [12]: tf = TagForm({'slug': 'create'}) In [13]: tf.errors Out[13]: {} -
Create subdomains like Shopify in pythonanywhere
My domain name is 'example.com' and I need to create subdomain for every store created in that site like 'store1.examaple.com', 'store2.examaple.com'. Code for every subdomain is the same. currently my project is deployed on pythonanywhere and I already have custom domain. So is it possible to dynamically create multiple subdomain in pythonanywhere same as Shopify ? -
Adding a transient ranking field to djangorest class and serializer
I am new to djangorest and am not sure how to even go about this. I have a Rest API that takes a post-request (with a list of parameters) and returns a list of items from a model via a serializer. It all works great. I need to add a "rank" or rather a "relevancy score" to the items in my returned list. I can calculate the rank fine - I am doing it in the REST view - what I don't understand is how to pass the rank back with the serialized model class in the response. I could create an entirely new object and pass it with the item ids.... but what I would rather do is attach a transient field: {"rank": value } to each item in my list. Can I do this? -
How to apply filtering after serialization with Filter backend in DRF?
For the context I will explain the current flow: The model Document has a field document_signing_status which has 2 possible values: SIGNED/NOT_SIGNED. However, in the serializer, I override this field by having a custom SerializerMethodField() which applies some modification and instead of returning 2 values it can return 4: "EXPIRED", "WAITING_FOR_ME", "WAITING_FOR_OTHERS", "SIGNED" I don't want to store these values on the database level, but I need to apply filtering. Right now I use filters.FilterSet, but it uses QuerySet so I can't simply specify filtering fields and pass "EXPIRED" since, in the model field there is only "SIGNED" or "NOT_SIGNED". How should I approach this issue? I thought about iterating the query set and applying modifications for that field to have one from possible 4 options, instead of 2, but not sure if it is a valid point and if even possible. -
the image not displayed when i want to retrieve it from database : Django -xhtml2pdf
I need to get an image from database (entered by me on Django-admin interface), and i need to display it in my pdf generated. I have first get the image for each specifc user logged in like that in the views.py: image1_full = CustomerPersonalData.objects.get(user_related=request.user) obj_image1 = CustomerPersonalData._meta.get_field('image1') value_image1 = str(obj_image1.value_from_object(image1_full)) in the pdf_generated.html, I have define it like that: <img src={{value_image1.url}} /> ----> but like that there is no image displayed. PS: am using xhtml2pdf -
Doubts about Django models primary_key and UniqueConstraint for composite primary key
Usually primary key means also unique (and more conditions like not null, etc.). If I have UniqueConstraint with 2 fields, including the primary key, I have 2 unique conditions (one because the primary key and another because the constraint). So that's is not the same than having a composite primary key with only one unique condition. For example, with this code: class MyClass (models.Model): field1=models.IntegerField(primary_key=True) field2=models.IntegerField() UniqueConstraint(fields=['field1', 'field2'], name='ConstraintName') Can I insert these values (1,1) and (1,2) since the field1 value is repeated and the primary key should be unique? In that case, what's the real meaning of primary key on Django models? Doesn't it imply a unique condition? Thanks a lot and regards. -
Adding frontend (Next.js/React) to django-oscar
I want to create an ecommerce app using django-oscar framework and self-build frontend. The docs explain how to change the website appearance but the base is build with bootstrap and standard django templates. To completely change storefront I just point at another folder in my project directory and create duplicated templates with the same name (for example if in framework there is product page then I need to create product_details.html template and code there). Now- I want to use Next.js (since React itself isn't great in terms of SEO) to build the storefront. What should be my approach? I don't know a lot of Next.js yet, in React I guess I would just generate .js file for every template (index.js for main page, product_details.js for products etc.). The REST API isn't a problem, there is django-oscar DRF version ready to use. -
Build failed when I build a docker container (Ubuntu 22.04 LTS), Error: Client.Timeout exceeded while awaiting headers
When I am building a docker container this error occurs: Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers) ERROR: Service 'migrate' failed to build : Build failed It's worked perfectly before, now I am getting this error. -
Django CRUD the data is not visible even though it is added in database
I am new to django and postgresql,I am currently doing CRUD and I have been able to make the create and insert page,I am able to ad the details as it appearas in the database but it isnt appearing in the read page here's the code in views.py def show_cat(request): showcategory = Categories.objects.filter(isactive=True) #print(showall) serializer = CategoriesSerializer(showcategory,many=True) #print(serializer.data) return render(request,'polls/show_cat.html',{"data":serializer.data}) def insert_cat(request): if request.method == "POST": insertcategory = {} insertcategory['category_name']=request.POST.get('category_name') insertcategory['category_description']=request.POST.get('category_description') form = CategoriesSerializer(data=insertcategory) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('categories:show_cat') else: print(form.errors) return redirect('categories:show_cat') else: insertcategory = {} form = CategoriesSerializer(data=insertcategory) if form.is_valid(): print(form.errors) return render(request,'polls/insert_cat.html') urls.py from django.urls import path from categories import views from django.urls.conf import include from django.conf import settings from django.conf.urls.static import static urlpatterns=[ path('',views.show_cat,name="show_cat"), path('insert_cat/',views.insert_cat,name="insert_cat"), path('edit_cat/',views.edit_cat,name="edit_cat"), path('del_cat/',views.del_cat,name="del_cat") ] I have tried everything possible but I am not able to display the data on the 'read'page,please help -
Creating a game picking web app in django
I am having issues in writing code for my game picking app, I managed to get a model form working for admin game insertion to database (matchweek, game, result etc) but I am having trouble with writing a form and logic for user picks. I would like user to choose a week (I did this part) and then the form should have all games for that week, user and user picks. The logic is that you get one point for each game guessed right in a week, and than the user with most points gets 25 points for the summary point table. I am trying to get this gamepicking form working with formsets but I am not really sure anymore if my database logic is okay, I have a table called Bet containing user,game_id (FK) ,user pick. I am really stuck on this part. -
Why Django Commands are working well outside the virtual environment and doesn't work inside virtual environment
I recently installed Django on my machine, I installed virtualenv, virtualenv-wrapper and i even customized the ~/.bashrc file but; Some commands like "python3 manage.py startapp" give me an error when inside the virtual environment but do work outside the virtual environment, I wanna know why? why is it that django commands dont run in zsh shell but do run in bash shell? Note:: Am writing all the commands in the folder containing manage.py and the django local server is already running And please don't downvote my question because I really wanna know? My working terminal1 My working terminal2 -
In django, Redirection is not working after performing edit and delete
I am trying to perform Edit and Delete functionality in Django. After edit and delete it is not redirecting me to the URL provided in parameters. Rather it stays on current URL. I want to redirect to adduser page but it redirecting me to edituser and deleteuser after performing edit and delete.I am sharing code for edit function here. urls.py path('edituser/<uid>', views.edituser, name="edituser"), views.py def edituser(request, uid): if request.method == "POST": if request.POST.get('firstname') and request.POST.get('lastname'): saverecord = AddContact() saverecord.id = uid saverecord.f_name = request.POST.get('firstname') saverecord.l_name = request.POST.get('lastname') saverecord.save() viewRecords = AddContact.objects.filter(subscribe='subscribe') return HttpResponseRedirect(reverse("adduser"), {'adduser': viewRecords, args=(AddContact.pk)) else: viewRecords = AddContact.objects.filter(subscribe='subscribe') messages.error(request, "Error During Editing of User") return render(request, "adduser.html", {'adduser': viewRecords}) Adduser.html Edit and Delete button <a href="#userEditModal-{{forloop.counter}}" data-toggle="modal" class="btn btn-primary"><span class="fa fa-pencil"></span> Edit</a> <a href="{% url 'deleteuser' id=vr.id %}" class="btn btn-danger" data-target="success-modal-delete"><span class="fa fa-trash"></span> Delete</a> Edit model {% for vr in adduser.adduser.all %} <div class="modal fade" id="userEditModal-{{forloop.counter}}" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <form method="POST" action="{% url 'edituser' uid=vr.id %}" class="needs-validation" novalidate> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Edit User Data</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!--Form Start--> <div class="form-row"> <div class="form-group col-md-6"> <label for="FirstName">First Name<span style="color:#ff0000">*</span></label> <input type="text" … -
Why am I not able to reset the django admin password?
I run this command python manage.py changepassword <project_name> to change the password and once I set the password and retype it for the confirmation it just says your password didn't match even though the passwords were exactly the same. I tried many times and still couldn't reset it. what is the problem exactly and the solution to it?enter image description here -
Add filesize validation for django form file upload
I am using django for file upload, it accepts excelfile as external_id_file and parse in def clean_external_id_file class UserGroupCreateForm(forms.Form): class Meta: model = LineUserGroup fields = ("group_name", "is_selected_all_user") def clean_external_id_file(self): external_id_file = self.cleaned_data.get('external_id_file') if external_id_file is not None: try: external_id_dict = get_data(external_id_file) except Exception as e: self.add_error( "external_id_file", f"please check if this is correct excel file") return try: sheets = list(external_id_dict.keys()) data = external_id_dict.get(sheets[0])[1:] if len(sheets) > 0: external_id_list = [str(x[1]) for x in data] except: self.add_error( "external_id_file", f"not correct excel file") return However in this case, I want to limit the file size for example 2MB. I have some basic question. I can add some validation in this form ?(I prefer this way) or I should make something in javascript? Any help appreciated. -
Django login problems
I can register new user. But after logout, I cannot login again .It shows user does not exist. But when I checked admin panel I get hashed password. forms.py class UserLoginForm(forms.Form): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") if email and password: user = authenticate(email=email, password=password) if not user: raise forms.ValidationError("User Does Not Exist.") if not user.check_password(password): raise forms.ValidationError("Password Does not Match.") if not user.is_active: raise forms.ValidationError("User is not Active.") return super(UserLoginForm, self).clean(*args, **kwargs) views.py def login_view(request): # users will login with their Email & Password if request.user.is_authenticated: return redirect("/") else: title = "Login" form = UserLoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") # authenticates with Email & Password user = authenticate(email=email, password=password) login(request, user) return redirect("/") context = {"form": form, "title": title } return render(request, "accounts/login.html", context) -
How to update data in Database when status_choise removed from models
In models I had status choices for status = models.CharField(max_length=50, default="FIELD_1", choices=STATUS) like this: STATUS = ( ('FIELD_1', _('value FIELD_1')), ('FIELD_2', _('value FIELD_2')), ('FIELD_3', _('value FIELD_3')), ('FIELD_4', _('value FIELD_4')), ('FIELD_5', _('value FIELD_5')), ) I have removed ('FIELD_5', _('value FIELD_5')), and ('FIELD_4', _('value FIELD_4')), from choices. How can I update database status value in Database to FIELD_1 when it was FIELD_5 or FIELD_4 -
405 (Method Not Allowed) DJANGO REST
Minha aplicação roda perfeitamente localhost, mas quando eu subo para o servidor, que é um Windows server, o método PUT, POST, simplesmente para de funcionar e acusa '405 (Method Not Allowed)', entre várias tentativas, mexendo no webconfig, uma hora consegui fazer um POST, mas já mexi tanto que não sei mais como voltar... meu webconfig webconfig -
How to convert beforefilter from cakephp to Django?
I am moving website created in cakephp to Django rest framework. In cakephp, every controller has parent class as AppController. There is beforefilter in AppController which is checking authentication/permission and depending on permission other function is being called to set value of public variable present in that class. class AppController extends Controller { public temp1 = ''; public temp2 = array(); public function beforeFilter(){ } } I want to create it using Django Rest Framework and send json response to the react app. As far as login authentication is concerned, I used simple-jwt. class index(APIView): def get(self,request): data = {} return JsonResponse(data) Do I need to implement AppController in django separately, create function beforefilter() and call beforefilter() every time I create any api and What about checking whether user is authenticated or not ? Is there any simpler method to apply beforefilter? -
My unit tests don't work with multiple databases
I'm working on a project where there are two databases, and I need to create unit tests for my models and etc. these are my databases: DATABASES = { 'default': {}, 'auth_db': { 'NAME': 'name' 'ENGINE': 'django.db.backends.postgresql', 'USER': 'user' 'PASSWORD': 'password' 'PORT': 5432 'HOST': 'localhost }, 'base': { 'NAME': 'name, 'ENGINE': 'django.db.backends.postgresql', 'USER': 'user', 'PASSWORD': 'password', 'PORT': 5432, 'HOST': 'locahost, } } At first I'm creating only the unit tests of the models from django.test import TestCase from base.models import User class UserModelTest(TestCase): @classmethod def setUpTestData(cls): # Set up non-modified objects used by all test methods User.objects.create(first_name='Big', last_name='Bob') def test_first_name_label(self): author = User.objects.get(id=1) field_label = author._meta.get_field('first_name').verbose_name self.assertEqual(field_label, 'first name') But when I do sudo python3 manage.py test, it returns me the error: AssertionError: Database queries to 'base' are not allowed in this test. Add 'base' to base.tests.test_models.UserModelTest.databases to ensure proper test isolation and silence this failure. When I was working with just one database, it wasn't giving a problem, however, when I separated it, I had this problem. I've looked everywhere and haven't found a solution.