Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django get the value enside formvalid
I am trying to obtain the value of the val variable that is inside form_valid but I cannot obtain it. Does anyone have any idea what I'm doing wrong? return reverse_lazy('cotizando', kwargs = {'pk': self.kwargs["pk"], 'num_cot':self.value}) class Cotizar(CreateView): template_name = "cotizar.html" model = Servicio fields = ['no_servicio', 'precio'] #success_url = '/Cotizar/48' def form_valid(self, form): value = 90 a = Cotizacion( numcot = "{}".format(numerocotizacion()) ,empresa_id = self.kwargs["pk"] ) a.save() form.instance.cotizacion_id = cotizacion_id = a.pk return super().form_valid(form) def get_context_data(self, **kwargs): contexto = super().get_context_data(**kwargs) contexto['productserv'] = Servicio.objects.all() contexto['empresa'] = Empresa.objects.get(pk = self.kwargs['pk']) return contexto def get_success_url(self, **kwargs): #slug = Empresa.objects.get(id=self.kwargs["pk"]).slug return reverse_lazy('cotizando', kwargs = {'pk': self.kwargs["pk"], 'num_cot':self.value}) # return reverse_lazy('v', kwargs={'pk': self.object["pk"]}) -
I'm trying to do a CRUD with Python, and the data display is having a conflict between the tables
Ok, before anything I just want to make clear that english is not my first language and I've never posted a question here before, so I apologise beforehand if this all seems confusing, I'll try to be as direct and clear as possible here. I don't know what else to do at this point since I don't know anyone that deals with similar code, so I'm hoping someone here can maybe identify what I'm doing wrong here. T^T Basically, I'm doing this college assignment where I have to make a CRUD in Python for a motorcycle dealership (in my case I'm doing it with the django library, and using SQLite to manage the database). Everything is going well, except for the part where it displays the data (it's basically creating link to page on a local server on the computer. I'm not exactly sure how to describe it), and in the main page it displays a few tables, with data from the database tables (I have two, right now, one for client data and the other for the motorcycles). Problem is: the data input works just fine, but whenever I try to make the page display the data from the … -
How to run Django in Python?
I am trying to install django in python. This is my code. conda create -n djangoenv python=3.8.5 anaconda conda activate djangoenv conda install -c anaconda django django-admin startproject website python manage.py runserver when I run the last line of code I get the following error python: can't open file 'manage.py': [Errno 2] No such file or directory I am trying this code (djangoenv) C:\Users\Action>django_project\manage.py and this code (djangoenv) C:\Users\Action>djanago_project\manage.py runserver Both codes are opening the script file, but are not running the Django and giving me the URL Does anyone have any suggestions to amend the code? -
I'm trying to build Project Management API
actually i have many problems here I'm going to list a few of them I'm using django rest framework to build Project Management API I have 3 end points Projects, tasks, group my first problem is in group end point I want to list all groups that the loged user created and all groups that the loged user is member in . my second problem is I want the group members assign actions in the tasks of the project in the group . and last one in in my post form in task and groups project variable return all projects create in the server so I want only retun the project that the current user created . here is my model class Project(models.Model): """ here we have all projects data and the owner of the project we can add more fields . """ created = models.DateTimeField(auto_now_add=True,blank=False) #the time of creating the project title = models.CharField(max_length=100, blank=False, default='') # project title owner = models.ForeignKey('auth.User', related_name='projects', on_delete=models.CASCADE) # project owner class Meta: # we order with the new one ordering = ('-created', ) def __str__(self): return self.title class Task(models.Model): """ Task table here we create a relation '' """ title = models.CharField(max_length=100, … -
Channels django nginx 502
I ran into a problem once I install and add "channels" to the settings and after that to the asgi file. Server crashes, I get 502 and nginx won't start. How can I add these channels and start working already ASGI_APPLICATION = "mysite.asgi.application" application = ProtocolTypeRouter({ "http": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter([ ]) ), }) help, I'm sure a lot of people have come across this, thanks -
Auto reloading no longer working after Django 1.11 to 3.2 upgrade
After upgrading an old inherited codebase from Django 1.11 to 3.2.13, I've found that Django no longer automatically reloads the server whenever a file change occurs. I've looked at the logger and it does say the the reloader is watching for file changes. After performing one change in the codebase and hitting save, the logger does say that it has detected a file change; however, nothing actually happens and the changes aren't reflected anywhere until you manually restart the server. If I make any further changes, there are no further logger messages displayed about file changes. I've also noticed that any version of Django before 2.2 seems to work in terms of reloading properly. It was only after upgrading to 2.2 and 3.2 that I noticed any issues. Here is a snippet from the logs. Staring threads ['manage.py', 'runserver'] System check identified no issues (0 silenced). May 12, 2022 - 20:07:04 Django version 3.2.13, using settings 'api.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [none] 2022-05-12 20:07:21,827 django.utils.autoreload INFO /api/settings.py changed, reloading. Has anyone else run into this issue before? For reference, I'm currently testing on the following environment: MacOS Monterey (12.3.1, M1) Python 3.9.12 (have also … -
How to use bootstrap with xhtml2pdf?
I need to render PDF files dynamically in a Django web app. I understand there are 2 options : Render an html template file then convert it to a PDF file. I used xhtml2pdf Python library. The issue is that the template I want to use has bootstrap and it isn't supported by xhtml2pdf. Actually no javascript is supported and the generated PDFs are horrible. I have to write the html / css myself which I don't want to. How to solve this problem ? Is there an alternative library ? Convert a webpage into a PDF file directly -
How to login into a django backend in jest tests?
I have a django server that is running the graphQL backend. I need to authenticate a user so I can test against the /graphql endpoint. I have search and tried all the solutions for logging in. I keep getting status code 200 but if I read the html I am still on the login screen. If I subsequently try to hit the graphql endpoint I get a message that I need to be logged in to do it. I tried using withCredentials but it says that is not allowed. I have disabled CSRF for login for so that is not the issue. Any idea what is wrong with this code since it does not login and keep the session? import axios from 'axios'; import {wrapper} from 'axios-cookiejar-support'; import {CookieJar} from 'tough-cookie'; let f = new FormData() f.append('username','admin') f.append('password','password') const jar = new CookieJar(); const client = wrapper(axios.create({jar})); let login_resp = await client.post('http://localhost:3031/admin/login', f,{headers: {'Content-Type': 'application/json'}}); console.log(login_resp.status) console.log(login_resp.data) -
Django DateField validators are not running
I have a DateField as part of a form. date = forms.DateField( required=True, input_formats=[DATE_INPUT_FORMATS] ) When I view the form, on the front end, and I enter garbage in to the date field, Django doesn't throw a forms.ValidationError, and instead proceeds to execute the forms clean() method. I have tried adding my own custom validation method to the DateField: def validate_date_field(dateval): raise forms.ValidationError("date error...") date = forms.DateField( required=True, input_formats=[DATE_INPUT_FORMATS], validators=[validate_date_field] ) Even when my validate_date_field function is set up to always return a validation error, it does not execute. Instead, and again, Django proceeds to execute the code in the forms clean() method... What's going on ? -
Django class based custom error page handler
Is it possible to write a class based (not function) custom error page handler? for example this: def handler404(request, *args, **argv): response = render_to_response('404.html', {}, context_instance=RequestContext(request)) response.status_code = 404 return response but with class -
How to send JSON format data in postman to django models that have a foreign key to another model?
I have tried to send a POST request to django views.py file using postman. It was working when I sent a POST and GET request to django models that haven't ForeignKey field. However, when I tried to send a POST request to a django model that have a ForeignKey field, it wasn't working. My question is how to send a JSON format data using postman to django models that have a Foregin Key field. The models are as follows: class Article(models.Model): authorId=models.CharField(max_length=100) authorResidence=models.CharField(max_length=100) communtId=models.CharField(max_length=100) content=models.TextField() contentId=models.CharField(max_length=100) source=models.CharField(max_length=100) timestamp=models.IntegerField() title=models.CharField(max_length=100) class Interactions(models.Model): userId=models.CharField(max_length=100,unique=True) location=models.CharField(max_length=100) eventType=models.IntegerField(unique=True) articleId=models.ForeignKey(Article,on_delete=models.CASCADE) communityId=models.CharField(max_length=100) source=models.IntegerField() timestamp=models.IntegerField() I have tried in this way (in postman): { "userId":"153344", "location":"Ethiopia", "eventType":"1", "articleId":"67353536", "communityId":"1234567", "source":"1", "timestamp":"123456" } As you can see the articleId is a foreignKey field. Here is the output: { "articleId": [ "Invalid pk \"67353536\" - object does not exist." ] } -
file extentions in Django
I have created a file upload website where I want to allow users to upload files in pdf, ppt, doc, txt, and zip format. I am using the HTML form to upload files. model.py class Upload_Notes(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) uploadingdate = models.CharField(max_length=30) branch = models.CharField(max_length=30) subject = models.CharField(max_length=50) notesfile = models.FileField(null=True) filetype = models.CharField(max_length=30) description = models.CharField(max_length=200, null=True) status = models.CharField(max_length=15) def __str__(self): return f'{self.user} notes' view.py def upload_notes(request): if request.method=='POST': branch = request.POST['branch'] subject = request.POST['subject'] notes = request.FILES['notesfile'] filetype = request.POST['filetype'] description = request.POST['description'] user = User.objects.filter(username=request.user.username).first() Upload_Notes.objects.create(user=user,uploadingdate=date.today(),branch=branch,subject=subject,notesfile=notes, filetype=filetype,description=description,status='pending') messages.success(request,f"Notes uploaded from {request.user.username} successfully!") return redirect('/view_mynotes') return render(request,'user/upload_notes.html') I have tried to do it by following this tutorial but it doesn't work for me. please help me to achieve this -
data._mutable= True in Django rest framework
I have seen this many times and looked it everywhere but couldn't figure out what it actually means and is it mandatory? I have not used this data._mutable = True or False in my code before and I am not sure whether I should be using it or not. The code snippet looks somewhat like this. def update(self, request, *args, **kwargs): instance = self.get_object() data = request.data if data.get("something") == "null": data._mutable = True data["something"] = None data._mutable = False Why do we need to assign True or False to the private attribute _mutable of data object.?? -
Django: CSS File Not Loading
I have an app in Django, where I am creating a web page. When I go to the proper URL, the HTML page, with Bootstrap does load, but my CSS doesn't load. Below, I wanted to color the h1 Blue, but it doesn't appear, it's black. I have added the HTML file, CSS file, and File Tree, below. Thank you for helping and let me know if you need more information. HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Amodh Dhakal | Portfolio</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="{% static 'mysite/style.css' %}"> </head> <body> <h1>Hello</h1> </body> </html> CSS h1 { color: blue; } File Tree -
Django sub-admin permissions
I am creating a project in which colleges can post notice for their students.That means colleges are my client. Right now every college is able to see the data of each other's students in admin panel. I want that college can see only their students in admin panel. I am new in django and don't know how to do it. Please help. -
django.db.utils.IntegrityError: NOT NULL constraint failed after reseting migrations
I need to save an object that contains a file and some other data. Although the file is stored on the /media folder, the entity is not saved in the database since saving it triggers an integration error. django.db.utils.IntegrityError: NOT NULL constraint failed: app_eeg.filename 'filename' was a field I deleted and I already deleted the migrations folder and did the following commands: python3 manage.py makemigrations app python3 manage.py migrate app Models.py class EEG(models.Model): file = models.FileField(null=False) status = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) report = models.ForeignKey(Report, verbose_name=('report'), on_delete=models.CASCADE, related_name='%(class)s_report', null=True) operator = models.ForeignKey(Operator, verbose_name=('operator'), on_delete=models.CASCADE, related_name='%(class)s_operator', null=False) patient = models.ForeignKey(Patient, verbose_name=('patient'), on_delete=models.CASCADE, related_name='%(class)s_patient', null=False) How can I fix this error from happening? -
A MultiSelectField with a select2 widget is not properly working for EDIT in Django
I have a form I am trying to understand its behaviour in Django. The form code looks like : class RequestForm(forms.ModelForm): TIMEPOINTS = ( ("1M" , "1M"), ("2M" , "2M"), ("4M" , "4M"), ("6M" , "6M"), ("9M" , "9M"), ("1Y" , "1Y"), ("2Y" , "2Y"), ("3Y" , "3Y"), ("4Y" , "4Y"), ("5Y" , "5Y"), ) timepoint = forms.MultipleChoiceField(choices=TIMEPOINTS) def __init__(self, *args, **kwargs): super(RequestForm, self).__init__(*args, **kwargs) self.fields['timepoint'].required = False class Meta: model = Request fields = '__all__' exclude = ('request_task_id', 'request_status',) widgets = { 'timepoint': forms.Select(attrs={'class': 'select2 timepoint form-control'}) } I have a classic view @login_required def edit_request(request, pk): data_request = Request.objects.get(id=pk) form = RequestForm(instance=data_request) if request.method == 'POST': form = RequestForm(request.POST, instance=data_request) if form.is_valid(): new_req = form.save(commit=False) new_req.created_by = request.user new_req.save() messages.success(request, ' Request Edited Successfully') return redirect("data-requests") else: form = RequestForm(instance=data_request) context = { 'form': form, 'data_request' : data_request, } return render(request, 'extractor/datarequest_edit.html', context) The problem with this code and the behaviour hat I dont undertant is this : 1- The form works fine when I select many timepoints in the form, it saves as a charfield 2- When I want to edit I cannot find my options on the field 3- When I pick only one opton, it … -
Private Object Field in Django Admin
I'm wondering what the best way to have an editable field (by admins) for some object in Django admin that can't be viewable on the public site. For example, a notes section for content authors with conventions or instructions that a front-end dev can't accidentally render in a template. Something like: class SomeModel(Model): internal_notes = CharField(max_length=1024, public=False) So some object, o, can't be rendered in a template: {{ o.internal_notes }} -
How to add more fields to an UpdateView using model: User?
I need to add more fields to my "edit profile" page because when someone registers they only have to fill in 2 fields (inputs) but when they go to "edit profile" they appear as 8 fields in the form. Does anyone have an idea how to add more fields such as: social media, country, address etc. to the "User" model (it's the one I'm using) it comes from here: from django.contrib.auth.models import User views.py class EditProfilePageView(generic.UpdateView): model = User template_name = 'Usuarios/edit-profile.html' fields = '__all__' success_url = reverse_lazy('profile') def get_object(self): return self.request.user -
Django How to properly upload image to form?
This is my code associated with the form: models class Date(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=64, null=True) class Photo(models.Model): date = models.ForeignKey('Date', on_delete=models.CASCADE) image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/') # form class DateForm(forms.ModelForm): image = forms.ImageField() class Meta: model = Date exclude = ('user',) # view class CreateDateView(LoginRequiredMixin, CreateView): template_name = 'app/date/form.html' form_class = DateForm def form_valid(self, form): form.instance.user = self.request.user form.save() # by the way why do I save this form? Is it okay to save it in form_valid method? photos = self.request.FILES.getlist('image') for photo in photos: Photo.objects.create(image=photo) return super().form_valid(form) The issue is how to save Photo objects if it requires a Date model id. It raises NOT NULL constraint failed: app_photo.date_id As I understand I have to write something like: Photo.objects.create(date=date_from_the_form, image=photo) But how to get the pk from the Date model? Hope you understand my problem, if any questions don't hesitate to write them down below in the comments section. Thanks in advance! Error -
django ajax project- basket - collecting values in array
in my django store i have basket wich in views.py have class : class BasketAddView(View): def post(self, request, *args, **kwargs): basket = Basket(request) product_id = str(request.POST.get('productid')) product_size = str(request.POST.get('productsize')) product_qty = str(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) #it was id and should be p basket_size_table = [] basket_size_table.append(product_size) basket.add(product=product, size=product_size, qty = product_qty) basketqty=basket.__len__() response = JsonResponse({'size': basket_size_table,'product' : product_id, 'qty': basketqty, }) return response web inspector in output in console show that i have only last size in array [] 1 but i would like to have a collections of sizes in one array. -
Trying To Retrieve Name Instead of Primary Key, But DRF complains of Value Error. If I try to fix it, I got other errors too
My Models: def upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class StreamPlatform(models.Model): name = models.CharField(max_length=200) about = models.TextField(max_length=2000) website = models.URLField(max_length=2500) def __str__(self): return self.name class WatchList(models.Model): title = models.CharField(max_length=250) image = models.ImageField(_('Image'), upload_to=upload_to, default='images/default.jpg') storyline = models.TextField(max_length=2000) platform = models.ForeignKey(StreamPlatform, on_delete=models.CASCADE, related_name='watchlist') active = models.BooleanField(default=True) avg_rating = models.FloatField(default=0) number_rating = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title My Serializers: class WatchListSerializer(serializers.ModelSerializer): platform = serializers.CharField(source='platform.name') class Meta: model = WatchList fields = '__all__' extra_kwargs = {'avg_rating': {'read_only': True}, 'number_rating': {'read_only': True}} def create(self, validated_data): return WatchList.objects.create(**validated_data) class StreamPlatformSerializer(serializers.ModelSerializer): watchlist = WatchListSerializer(many=True, read_only=True) class Meta: model = StreamPlatform fields = '__all__' My View: class WatchListAV(generics.ListCreateAPIView): permission_classes = [AdminOrReadOnly] parser_classes = [MultiPartParser, FormParser] queryset = WatchList.objects.all() serializer_class = WatchListSerializer pagination_class = WatchListLimitOffsetPagination filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['title', 'platform__name'] ordering_fields = ['avg_rating'] The issue I got is that Django Rest Framework complains in PostMan that: ValueError at /watch/list/ Cannot assign "{'name': '8'}": "WatchList.platform" must be a "StreamPlatform" instance. When I try to fix it like this in the WatchListSerializer: platform = serializers.PrimaryKeyRelatedField(queryset = StreamPlatform.objects.all(), source='platform.name',) I got a new error instead: ValueError at /watch/list/ Cannot assign "{'name': <StreamPlatform: Blah>}": "WatchList.platform" must be a "StreamPlatform" instance. When I commented out the error-prone code bits, … -
Get django username before editing it
Im using a django signal to post to an API based on the users username. If the user doesnt exist it creates a new one and posts to API . If im editing the user I cant acess the old username to change the API . I've also tried with pre_save but with no result . Lets say for example username is Nick if user does not exist it creates the API, if nick changes his username to NickyXX when i do username = instance.username i get the NickyXX therefore i cant acess the API .I know my approach is incorrect but I dont know how to get the original username. @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): username = instance.username if created: Profile.objects.create(user=instance) ### API SCRIPT ### .............. ################### CREATE A NEW USER ################### url = 'http://...' myobj = { "organization": { "canHaveGateways": True, "displayName": instance.username, "name": instance.username } } x = requests.post(url,json = myobj) x = x.json() print(x) orgID = x["id"] print(orgID) else: instance.profile.save() ################### FIND USERNAME ################### url = '...&search=' + username x = requests.get(url) x = x.json() print(x) ################### EDIT ################### myobj = { "organization": { "displayName": username, "name": username } } x = requests.put(url, json … -
Django rest framework wont display data when doing a filter
I haven't used Django RF in a while and I ran into a problem. I was trying to do an object.get() and I got an error that said It returned more than 1 (returned 2) so I changed the .get to .filter and It fixed my error issue but it won't show any data when going to the endpoint, even though when printing in the console it shows that I've received a queryset (but its an array, [, ]). Heres my ViewSet: class TeamViewSet(ModelViewSet): queryset = Team.objects.all() serializer_class = TeamSerializer permission_classes = [IsAdminUser] @action(detail=False, methods=['GET','PUT'], permission_classes=[IsAuthenticated]) def me(self, request): # return Response(request.user.id) try: team = Team.objects.filter(leader__user_id=request.user.id) print(team) except Team.DoesNotExist: team = None if request.method == 'GET': serializer = TeamSerializer(team) return Response(serializer.data) elif request.method == 'PUT': serializer = TeamSerializer(team, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) It's problem an easy fix, I've just haven't used Django RF in a while, Thanks for any help :) -
Input type doesn't shown when use models form - DJANGO
so i was copy modelsform code from website https://ordinarycoders.com/blog/article/django-file-image-uploads but when i run my code, there's no input type="file" on my developer tools. but when i tried print class at models.py and forms.py, it's work. I don't know why no input type="file". this is what must be shown this is what shown by my web but when i tried to give print to my function upload at views.py, suddenly it doesn't want work and error print here's my views.py code : from django.shortcuts import render, redirect from django.views.decorators.csrf import ensure_csrf_cookie from .forms import AudioForm from .models import Audio_store from MusicLockApp.forms import AudioForm @ensure_csrf_cookie def homepage(request): # return HttpResponse('homepage') return render(request, 'homepage.html') def decode(request): # return HttpResponse('about') return render(request, 'decode.html') def upload(request): if request.method == 'POST': form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main:upload') form = AudioForm() audio = Audio_store.objects.all() return render(request=request, template_name='homepage.html', context={'form':form, 'audio':audio}) urls.py : from django.contrib import admin from django.conf.urls import url from . import views from django.urls import path, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path("upload", views.homepage, name="upload") ] if settings.DEBUG: #add this urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <div class="col-md-6"> {% block content %} {% …