Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django html display from model
I need on my html page to display data from Profesor and Ucenik model: ime, prezime, jmbg. {{profesor.ime}} {{profesor.prezime}} {{ucenik.ime}} {{ucenik.prezime}} {{ucenik.jmbg}} my profile page id dynamic, need to display profesor data or if ucenik to display ucenik data what i need to add on my views.py models.py class Profesor(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) ime = models.CharField(max_length=200, null=True) prezime = models.CharField(max_length=200, null=True) class Ucenik(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) ime = models.CharField(max_length=200, null=True) prezime = models.CharField(max_length=200, null=True) jmbg = models.IntegerField(null=True) urls.py path('profesor/', views.profesor, name='profesor'), path('ucenik/', views.ucenik, name='ucenik'), path('posetioc/', views.posetioc, name='posetioc'), path('profil/<str:pk>/', views.profil, name='profil'), ] views.py def profesor(request): return render(request, 'pocetna_profesor.html') def ucenik(request): return render(request, 'pocetna_ucenik.html') def profil(request, pk): return render(request, 'profil.html') HTML: {% extends 'base.html' %} <title>profesor</title> {% block content %} <body> {% include 'navbar.html' %} <h1>Ime:</h1> {{profesor.ime}} </body> {% endblock %} -
django appending form inside form with javascript called submit button
i have multiple form inside my template and i want to appending form div with add button like this <div id="Partform" class="card-body"> <div id="netformdiv" class="netformdiv"> <div style="display: flex;flex-direction: row" id="netwindow"> {{ formnetpriod.activity|as_crispy_field }} {{ formnetpriod.material|as_crispy_field }} {{ formnetpriod.days|as_crispy_field }} </div> </div> <div id="btnnetwindow"> <button style="width: 50px;height: 50px" onclick="addnetwindow()" class="btn btn-success">+</button> <button style="width: 50px;height: 50px" onclick="removenetwindow()" class="btn btn-danger">-</button> </div> </div> the javascript in my template for add or minuse form field is like this: <script> function addnetwindow(){ var form = document.getElementById("netwindow") var formBody = document.getElementById("netformdiv") var formcpy = form.cloneNode(true); formBody.append(formcpy); } function removenetwindow(){ let form = document.querySelectorAll("#netwindow") form[form.length-1].remove(); } </script> and the template view like this :enter image description here if i click on add button the div copied and when click minuse button the div remove last form but my problem is when i clicked on add or minuse button the submit button called and my page refreshed lost the appended form i think this is for django form to refresh the form data but how can i fix the problem. thank you -
Page not loading even after 200 status
I'm trying to redirect to the invoice page but nothing changes except the refresh this is the url.py urlpatterns = [ path('', User_login_view, name='login'), path('home/', HomePageView.as_view(), name='home'), path("nglm/", NGLMView.as_view() , name="nglm"), """ other urls for the sidebar""" path("createinvoice/", NGLINVAPI.as_view(), name="createinvoice"), path("nglinvoice/", NGLInvoiceTV.as_view(), name="nglinvoice") ] After login I go to "nglm" page where I input the customer details and click the submit button which calls the api "createinvoice". the class is shown below class NGLINVAPI(APIView): def post(self,request): if 'nglinv' == request.POST['formtype'] : data = { 'name': request.data['cname'], 'civilid': request.data['civilid'], 'ph':request.data['ph'], 'disc':request.data['disc'], 'bookno':request.data['Bookno'], 'tga':request.data['LAmount'], } p,ccreated = update_customerdb(data=data) l = update_gldb(data=data) data['cid'] = p.id iq,i = update_inventory(data=data,gl=l) lici = update_LICI(cid=p,lid=l,data=data) ninv = update_invoice(licid=lici,lid=l,cid=p,data=data,il = iq,items = i) invid = ninv.id NGLItemModel.objects.all().delete() base_url = '/nglinvoice/' query_string = urlencode({'pk': ninv.pk}) url = '{}?{}'.format(base_url, query_string) return redirect(url) return HttpResponseRedirect('home') this should have redirected me to invoice page "nglinvoice". the view is show below class NGLInvoiceTV(TemplateView): template_name = "pages/nglinvoice.html" def get(self, request): p = request.GET['pk'] inv = get_object_or_404(InvoiceModel, pk=p) context = {} context['segment'] = 'api' context['pagename'] = 'New GL API' context['object'] = inv return render(request,self.template_name , context) I have no issues up to this point. the problem is it doesn't show the page "nglinvoice.html", it just … -
Django - getting dropdown values
currently i am new to django and working with forms in django. i didn't know how to get the values from the dropdown and print it in python terminal ? Can anyone konw, How to get the dropdown values in Django and print it ? -
IntegrityError at /answer/ NOT NULL constraint failed: answer_answer.post_id
I have 2 models one for Question and one for Answer when i submitted answer form its throws me an error like this: IntegrityError at /answer/ NOT NULL constraint failed: answer_answer.post_id but when i added blank=True and null=True i can sumitted the form but i need to go to the admin and select the qustion i want the answer to be able to appear and that is not what i want. please how can i solve this error ? my models class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.user) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return str(self.user) the views def viewQuestion(request, pk): question = Question.objects.get(id=pk) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) class My_Question(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'body', 'category'] template_name = 'question.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Question, self).form_valid(form) class My_Answer(LoginRequiredMixin, CreateView): model = Answer fields = ['answer'] template_name = 'answer.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Answer, self).form_valid(form) the viewQuestion template: <div class="container"> <div … -
Tips to host an online MySQL server usable with Django
I want to make a Django website, with MySQL as the database. I have two of my friends working with me in different places for the development phase. The problem is, which online resources to use for the development time for the least/free cost' ? I have been thinking to use GitHub to store the website, but can't find any good MySQL free servers online (for the development period). Can someone suggest me? -
Django form input value for current image
My html form's image part: {% for photo in date.photo_set.all %} <div class="photo-wrapper-{{ forloop.counter }}"> <input type="file" name="current-photo-{{ forloop.counter }}" value="{{ photo }} accept="image/*""> </div> {% endfor %} Okay so this is a part of my form in Django. In form I show all current photos of model. When I submit the form I want to get that current photos in self.request.POST.keys(). But their key's values are empty like so: 'current-photo-1: [''], current-photo-2: ['']. As I understand the issue is in value attribute of <input> tag in my html form. It doesn't store any object-like stuff (image). How to make it actually store current photo. Hope you got it. If any questions, don't hesitate. Thanks! Note. I am pretty sure this information is enough for you to answer this question. -
Getting user credentials by email
I'm making a small solution to restore user credentials. I decided to try to do it with my algorithm. I request the user's mail and compare it with the database of postal addresses. If the mail exists, I want to send the user his credentials (login and password). I have already done the acceptance and verification of mail, as well as configured the sending of emails to postal addresses. But how to get access to credentials with only mail and the fact that the user is not logged in, I do not understand. I know that maybe my solution based on security is not very good, but there was interest and I really want to understand how to do it. It may be possible to make a quick login and get data from there, or it can do without it? As a result, I have to send the used as a message to views.py this data. views.py def recovery(request): if request.user.is_authenticated: return redirect("/accounts/exit/") else: if request.method == 'POST': email_form = UserRecoveryForm(request.POST) if email_form.is_valid(): email = email_form.cleaned_data['email'] try: send_mail("Восстановление учетных данных.", "message", "from@gmail.com", [email], fail_silently=False) except BadHeaderError: return HttpResponse('Ошибка в теме письма.') return render(request, 'registration/recovery_done.html') else: email_form = UserRecoveryForm() return render(request, … -
Django - How do I write a queryset that's equivalent to this SQL query? - Manging duplicates with Counting and FIRST_VALUE
I have Model "A" that both relates to another model and acts as a public face to the actual data (Model "B"), users can modify the contents of A but not of B. For every B there can be many As, and they have a one to many relation. When I display this model anytime there's two or more A's related to the B I see "duplicate" records with (almost always) the same data, a bad experience. I want to return a queryset of A items that relate to the B items, and when there's more than one roll them up to the first entered item. I also want to count the related model B items and return that count to give me an indication of how much duplication is available. I wrote the following analogous SQL query which counts the related items and uses first_value to find the first A created partitioned by B. SELECT * FROM ( SELECT COUNT(*) OVER (PARTITION BY b_id) as count_related_items, FIRST_VALUE(id) OVER (PARTITION BY b_id order by created_time ASC) as first_filter, * FROM A ) AS A1 WHERE A1.first_filter = A1.id; -
Sending data to external api url django rest_framework [Errno 2] No such file or directory
#My views file class CreateImageInfo(APIView): parser_classes = [MultiPartParser, FormParser] serializer_class = PostCreateUpload def post(self, request, *args, **kwargs): headers = {'Authorization': 'Bearer ' + c} url = 'https://api.logmeal.es/v2/image/recognition/type/{model_version}' file = PostCreateUpload(data=request.FILES) if file.is_valid(): file.save() image = file.data['image'] resp = requests.post( url, files={'image': open(image, 'r')}, headers=headers) return Response(resp.data, status=status.HTTP_201_CREATED) #Serializer File class PostCreateUpload(serializers.ModelSerializer): class Meta(): model = Identified fields = ('timestamp', 'image') #My Models file- class Identified(models.Model): # name = models.CharField(max_length=30) image = models.ImageField(upload_to='media', blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.timestamp ** current error coe displaying is "FileNotFoundError: [Errno 2] No such file or directory: '/images/media/art.onlin_281031686_1095087414692746_398359933098246564_n.jpg'"** -
Django: how to add slug to url tag in django?
i want to add a slug to url in using django, i have tried different slugs but there is something i am missing. <a href="{% url 'tutorials:tutorial' t.tutorial_category.slug t.tutorial_topic_category.slug t.topic.slug t.slug %}">{{t.title}}</a> this is my views.py def tutorial(request, main_category_slug, topic_category_slug, tutorial_slug): tutorial_topic_category = TutorialTopicCategory.objects.get(slug=topic_category_slug) topic = Topic.objects.filter(tutorial_topic_category=tutorial_topic_category) tutorial = Topic.objects.get(slug=tutorial_slug) context = { 'topic':topic, 'tutorial':tutorial, } return render(request, 'tutorials/tutorial.html', context) urls.py path("<slug:main_category_slug>/<slug:topic_category_slug>/<slug:tutorial_slug>", views.tutorial, name='tutorial') -
Using Regex Validators
How can I use Regex Validators in my Django project? (Current using Django 1.11) forms.py class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') To be more specific in 'full_name' , 'company' and 'note' fields I just want to allow digits and letters. In 'email' field want to allow digits , letters, "-" , "_" , "." and "@" characters. And in 'phone_number' field want to digits and "+" , "#" , "()" characters. -
Display media files with Django
I learn Django and I have a problem with display img in settings I add: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "moje_media") and in url.py I add static urlpatterns = [ //routing ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Problem is that img is uploading correctly but I have a problem with display that. For example - in my template I have img tag: <img src="{{MEDIA_URL}}{{film.plakat}}"> But it doesn't display that. I inspect img that and src contain "/media/plakaty/test.jpg". I go to Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ filmy/ login/ [name='login'] logout/ [name='logout'] ^media/(?P<path>.*)$ The current path, media/plakaty/test.jpg, matched the last one. What is wrong? -
return multiple images and their corresponding id in django
I want to send multiple images and their corresponding id from django to react.js. I tried to return dictionary of images with id as key in this format: {id1:image1, id2:image2} but i only recieved this in react.js {id1, id2} and there is no media images in recieved dictionary. How can return multiple images and thier corresponding id in django? -
how to create choices field from Enum Types Django
Enum class # waiting the customer ( not paid ) Waiting = "Waiting" # Waiting to the next ship Pending = "Pending" # on the way Shiping = "Shiping" # Done Done = "Shipped" Order Model How can I make Choices field from the Previous Class class Order(models.Model): customer = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) amount = models.PositiveIntegerField() status = models...! -
A better solution for the increasing number game?
I am remaking the question I made here based on the feedback given to me. If there is still something unclear in my question please let me know. Explanation for the game: Increasing number game where the user has to guess before the number is going to stop increasing. This is purely a random chance and is done by clicking on a button by the user. Number is calculated on the server side after each game. Number will be increasing by 0.01 starting from 1.00 until the number calculated on the server side. Solution I have come up with: Running a background process using apischeduler. Executing the number increasing function every 0.1 seconds which adds 0.01 to the current state of number and sends the state result to frontend using Django Channels. I am pulling and updating the state using database queries. When the end result (number) is reached, new number will be calculated and there will be a timer running before new game begins. That all this seems odd considering I am calling a function in the background every 0.1 seconds forever. I can not figure out how to complete the task differently though. Is there a better solution/more … -
How to set allowed characters in Django forms?
I want to set allowed characters for my forms. How can I do this limitation in Django 1.11? forms.py from django import forms from .models import Customer class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') -
Should I use .values_list(), .exists() or something else to check for existence?
I have a model with a string as primary key class Player(models.Model): player_tag = models.CharField(max_length=9, primary_key=True) [...] The player tag is unique to each player, and I retrieve batches of up to 30 player tags before either creating or updating them. However doing so requires me to check if the player tag already exists, and for that I know Django has .exists() method, that checks for the presence of an item inside a queryset. However I figured that would hit the database each time I looked for a player, which sounds less than ideal. I also thought about using a line like this : player_ids = models.Player.objects.values_list('player_tag', flat=True) Which would hit the db once and then I'd check against this list for presence. But I doubt this scales. (The player list can get very lengthy) Is there a better solution for this, something that would allow me to check for the existence of a string primary key while keeping the impact on the database minimal ? -
database design for conditional questions
i'm trying to implement a system where the user select a symptom and then questions related to that symptom will show up , but it must be related to previews answer this is what im thinking for now class Symptom(models.Model) : symptom = models.CharField(max_length=1000) class Question(models.Model) : previous_answer = models.IntegerField() question = models.CharField(max_length=1000) image = models.ImageField('image') symptom = models.ForeignKey(Symptom,on_delete=models.CASCADE) class Answer(models.Model) : answer = models.CharField(max_length=1000) question = models.ForeignKey(Question,on_delete=models.CASCADE) -
Grouping Wagtail CMS streamfield fields?
First of all, I wish everyone a good day. I want to group blocks that I created with StreamField. I am attaching an example video and image below. You can view the image here. https://youtu.be/VMfxVCGarf4 Thank you for your help, best regards. What do I want to do? All component list Sub column (Component #1) Sub column (Component #2) Sub column (Component #3) All html blocks Sub column (HTML block #1) Sub column (Component #2) Sub column (Component #3) -
best way to use docker push command
I have just managed to containerized existing Django project. Now, I am pushing it to the docker-hub but, notice some 500mb file is getting pushed on the server. does 500mb is normal while pushing it to the docker-hub or I have to ignore some of the fie like we do with .gitignore. -
Get anchor and all params in request path
For a development with django, I try to get the parameters of my url. my path : http://127.0.0.1:8000/categories/candy#bubblizz candy is my view avec #bubblizz is my id anchor. A lot of documentation on request items but impossible to find how to get the anchor {{ request.build_absolute_uri }} => http://127.0.0.1:8000/categories/candy {{ request.get_full_path }} => /categories/candy {{ request.path }} => /categories/candy {{ request.META.PATH_INFO}} => /categories/candy The goal is to test the presence of the anchor in the url. {% if bubblizz in request.anchor %}Yeah{% endif %} Does anyone have an idea? Or documentation that might help? Thanks -
Django self.request.FILES.getlist
So I have changed the input's name attribute to some custom name, but the view calls form_invalid method. Why my Form isn't saving (validating)? html: <tr> <th><label for="id_photo">Image:</label></th> <td> <input type="file" name="custom_photo_name" accept="image/*" required id="id_photo" multiple> </td> </tr> the form: class DateForm(forms.ModelForm): photo = forms.ImageField(required=False) class Meta: model = Date exclude = ('user',) the view: class UpdateDateView(LoginRequiredMixin, UpdateView): model = Date form_class = DateForm template_name = 'app/form/date_edit_form.html' @transaction.atomic def form_valid(self, form): date = form.save() self.request.FILES.getlist('custom_photo_name') # this returns an empty list [] return super().form_valid(form) Doesn't the self.request.FILES takes the values according to name attribute? Why can't I reach my files? -
Django serializer validation
I am using serializers for validation. when i am sending key with name ip_port which is a list in form-data postman then response is coming 'This field is required' for ip_port key. Also i am attaching an image of postman where i am getting the response. Please help anyone and thanks in advance.postman response while testing POST api views.py def post(self,request,format=None): data=request.data serializer=UserRequestFormSerializer(data=data) if serializer.is_valid(raise_exception=True): # breakpoint() serializer.save(user=self.request.user) # print(serializer.data) sdata=serializer.data return Response({'detail':'User Request Form created successfully','created_data':sdata},status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializers.py class UserRequestFormSerializer(serializers.ModelSerializer): ip_port = IPPortSerializer(many=True) district=serializers.CharField(source='user.district',read_only=True) class Meta: model=UserRequestForm fields='__all__' read_only_fields=['user','district'] def to_representation(self, instance): data = super().to_representation(instance) if instance.form_status == "REJECT": data['rejection_data'] = RejectionTableSerializer(instance.rejectiontable_set.last()).data return data def create(self, validated_data): ipport=validated_data.pop('ip_port') user=UserRequestForm.objects.create(**validated_data) if ipport: ls=[] for i in ipport: ls.append(IPPort.objects.create(**i)) user.ip_port.set(ls) return user models.py class UserRequestForm(models.Model): #All Foreign keys: observer_account_type = models.CharField(max_length=200, choices=ACCOUNT_TYPE, blank=True,default='USER') decision_taken_by=models.ForeignKey(User,on_delete=models.CASCADE,related_name='userrequestform_decision_taken_by',blank=True,null=True) user=models.ForeignKey(User,on_delete=models.CASCADE) ip_port=models.ManyToManyField(IPPort) #to be filled by the user: sys_date=models.DateField() sys_time=models.TimeField() target_type=models.CharField(max_length=200,choices=TARGET_TYPE) case_ref=models.CharField(max_length=200) case_type=models.CharField(max_length=200) request_to_provide=models.CharField(max_length=200,choices=REQUEST_TO_PROVIDE) mobile_number=models.BigIntegerField(validators=[mobile_regex_validator]) cell_id=models.CharField(max_length=200) imei=models.CharField(max_length=200) select_tsp=models.ForeignKey(Tsp,on_delete=models.PROTECT) duration_date_from=models.DateField() duration_date_to=models.DateField() duration_time_from=models.TimeField() duration_time_to=models.TimeField() user_file=models.FileField(upload_to='user_doc',blank=True,null=True) #to be filled by TSP and CYBERDOME form_status=models.CharField(max_length=200,choices=FORM_STATUS,blank=True,null=True,default='PENDING') admin_status=models.CharField(max_length=200,choices=FORM_STATUS,blank=True,null=True,default='PENDING') #for tsp replie requested_date=models.DateField(blank=True,null=True) replied_date=models.DateField(blank=True,null=True) #for cyberdome view approval_or_reject_date=models.DateField(blank=True,null=True) approval_or_reject_time=models.TimeField(blank=True,null=True) #For TSP to upload file after approval tsp_file=models.FileField(upload_to='tsp_doc',blank=True) class Meta: ordering = ('id',) def __str__(self): return str(self.mobile_number) class IPPort(models.Model): ip=models.CharField(max_length=200,validators=[ip_regex_validator]) port=models.IntegerField() date_from=models.DateField(blank=True,null=True) date_to=models.DateField(blank=True,null=True) time_from=models.TimeField(blank=True,null=True) … -
Django Storages (GCP) returns NULL if the app is deployed in Cloud Run
I am using Django Storages to upload images on GCP's cloud storage bucket and I accomplished this on localhost by following these steps - Created a private bucket on Cloud Storage. Created a service account with Storage Admin privileges and also generated a JSON key. Installed Django Storages for GCP and Pillow. Created relevant environment variables like GOOGLE_APPLICATION_CREDENTIALS, GOOGLE_CLOUD_PROJECT and GS_BUCKET_NAME. Wrote a POST & GET request and it works like a charm on local machine. However, when I deployed this on Cloud Run I am able to upload the images but I get NULL instead of the image's Authenticated URL in response while fetching the image via GET request. As, Cloud Run uses Compute Engine Default Service account So I decided to give it a Cloud Storage Admin permission and then I tried again but still no luck. How can I make this work?