Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass uploaded file from html to python script with django
my question is that I want users to upload tiff file in html and then I need to read and analyze the tiff file in other python script and pass the result back to html when some button is clicked. How can I achieve that in django? Thanks! -
update a model and create a pdf in the same moment in django
I try to update a model (factures) I used: in models.py class TypeFact(models.Model): type = models.CharField(max_length=50, verbose_name="Type") def __str__(self): return self.type class Factures(models.Model): num_fact = models.CharField(primary_key=True, max_length=50, verbose_name="Numero") type_fact = models.ForeignKey('TypeFact', on_delete=models.CASCADE, verbose_name='Type_Facture') importance = models.IntegerField(verbose_name="Importance",null=True, default=None, blank=True) closed = models.BooleanField(default=False) def __str__(self): return self.num_fact + "/" + str(self.type_fact) in forms.py I just create a field based of a model Typefact class FormFactClose(forms.Form): chosen = forms.ModelChoiceField( label="Choix", queryset=models.TypeFact.objects.all(), required=False, ) def clean(self): cleaned_data = super(FormFactClose, self).clean() khiar = cleaned_data.get("chosen") result=models.TypeFact.objects.filter(type=khiar) I try to update a model factures by views.py def close(request): if len(request.POST) > 0: form = FormFactClose(request.GET) if form.is_valid(): choix = form.cleaned_data['type'] filt = Factures.objects.filter(type_fact__id= choix) filt.update(closed=1) return render(request, 'close.html', {'form': form}) else: return render(request, 'welcome2.html', {'form': form}) # Le formulaire n'a pas été envoyé else: form = FormFactClose() return render(request, 'close.html', {'form': form}) I haven't an error but it not work In the samme moment I want to create a pdf for the list update, but i don't know how to do it I search a help -
Sending mail with django newsletter
I´m trying to use the django_newsletter app and I can understand how it works. Some can helpe me please? Anybody has used any other module to sending emails like this? -
Unable to send data of multipal queries to ajax call in django
And I want to pass two data queries result named mydata and yourdata, problem is when I send only mydata or yourdata then its working fine but when I send in context variable its not working at all , I am new in django so any kind of help would be appreciated thanks. @csrf_exempt def snippetrequests(request): import json mydata=changerequest.objects.filter(owner_id=request.user.id) yourdata=changerequest.objects.filter(user_id=request.user.id) mydata=serializers.serialize('json',mydata) yourdata=serializers.serialize('json',yourdata) if request.method == 'GET': context = { 'mydata':mydata , 'yourdata':yourdata } return HttpResponse(context, content_type="application/json" ) And I am getting Data from it using AJAX like this $.ajax({ url: '/snippetrequests/', type: 'GET', data={}, success: function(data) { // alert(data); alert(data) console.log(data) var div1 = document.getElementById('snippet'); }, failure: function(data) { alert('Got an error dude'); } }); -
How to use 'MinValueValidator' considering other model field?
How can I use MinValueValidator on a DateField based on another DateField on the same model class? Example code: models.py code: from django.db import models from django.core.validators import MinValueValidator class Edition(models.Model): submission_deadline = models.DateField( 'some text', help_text='some help text' ) committee_evaluation_deadline = models.DateField( 'some text', help_text='some help text', validators=[MinValueValidator(submission_deadline, message='some specific error message')] ) scientific_editor_evaluation_deadline = models.DateField( 'some text', help_text='some help text', validators=[MinValueValidator(committee_evaluation_deadline, message='some specific error message')] ) appraiser_evaluation_deadline = models.DateField( 'some text', help_text='some help text', validators=[MinValueValidator(scientific_editor_evaluation_deadline, message='some specific error message')] ) author_correction_deadline = models.DateField( 'some text', help_text='some help text', validators=[MinValueValidator(appraiser_evaluation_deadline, message='some specific error message')] ) appraiser_revaluation_deadline = models.DateField( 'some text', help_text='some help text', validators=[MinValueValidator(author_correction_deadline, message='some specific error message')] ) # other fields that are excluded from the form form.py code: class EditionCreateForm(forms.ModelForm): class Meta: model = Edition exclude = ['magazine', 'slug', 'appraisers', 'types', 'published'] The form will handle save method, so all validators will be triggered. I guess there is another easy way to do this so I don't have to make field by field validation on form (clean_field()) or model save to raise especific error message for every field. Anyone knows how to get the field value of DateField that I can use on my models' definition? -
How to make models in django which have different models inside them as different table columns?
I am new to django development and am stuck in a project that I am working on. I have been trying to create a website where multiple people can rent different furniture items for their houses, for a specified booking period, which can not overlap for someone else. Thus, I thought, I would create a furniture model and a booking period with a many to many relationship as shown below class booking_period(models.Model): booking_period_start = models.DateField(auto_now=False) booking_period_end = models.DateField(auto_now=False) booking_person_name = models.CharField(max_length=200) class Furniture(models.Model): furniture_type = models.CharField(max_length=200) furniture_owner_name = models.CharField(max_length=200) furniture_booking = models.ManyToManyField(booking_period) def __str__(self): return self.furniture_type Then in django admin, I added the furniture class so that we can add the models ourselves. The challenge is that a particular furniture can have multiple booking periods and they cannot overlap with each other. So, a furniture can have no booking period while other can have 5 or 10 booking periods. Also, different furniture items can have slightly different booking periods as well. So, if we add all the possible booking periods in the table booking period, it will end up taking a lot of space. It will be really helpful if someone could tell me the best way to do this, … -
How can I store my user history on the website in django?
I'm learning Django and I've got a question: how can I store my user history on the website in Django? For example, if user purchase an item from the shop, there should be a record in the database with an id of the item, it's cost and the status of the order(shipping, delivered, etc). I was thinking about making a table for each user and just store data here, but I think it is just waste of space. How should I store my user's history? P.S. I'm using Postgresql. -
DRF - routing additional HTTP methods for extra actions
I'm trying to implement routing additional HTTP methods for extra actions using django rest framework but am getting an error at runserver AttributeError: 'function' object has no attribute 'mapping' Can't figure out what the issue is - Django 2.1.2, Python 3.6.5 class CustomerAPIViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated, CustomerAdminPermissions) serializer_class = CustomerSerializer queryset = Customer.objects.all() @action(detail=True) def order_guide(self, request, **kwargs): instance = self.get_object() serializer = CustomerDetailSerializer(instance) return Response(serializer.data) @order_guide.mapping.put def order_create(self, request, **kwargs): instance = self.get_object() serializer = CustomerDetailSerializer(instance, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) -
Django - How to pass custom field value to database
I've made a ModelForm that has all of Student model's fields and one extra choice field added in the form. But now that I have passed the choice field I want to know how I'll ever pass it to the database, because let's say for example that I want to pass the picked name as the name of the object on the database, how would I do that? This is how the FormView is like with only the model fields being applied: class StudentDelete(generic.FormView): template_name = 'students/student_form_delete.html' form_class = DeleteStudentForm success_url = '/' def form_valid(self, form): form.save(commit=True) return super().form_valid(form) What would I need to do to add the choice field to the database in here (which is where I presume it goes) def form_valid(self, form): #logic to add the field to the database form.save(commit=True) return super().form_valid(form) Here's the form, for reference: class DeleteStudentForm(forms.ModelForm): choice = forms.ModelChoiceField(queryset=Student.objects.all(), required=True, help_text="Student Name") class Meta: model = Student fields = '__all__' -
Django settings.py Parentheses vs Square Brackets
Is there a functional difference between using parentheses vs square brackets in the settings files of django? INSTALLED_APPS = [ 'django.contrib.admin', ... ] vs INSTALLED_APPS = ( 'django.contrib.admin', ... ) There does not appear to be, but I just wanted confirmation. -
Passing a header value to a get request in django
I want to pass a value through the Headers of a get request. Im trying the below but it doesn't work, class ListCategoriesView(generics.ListAPIView): """ Provides a get method handler. """ serializer_class = CategorySerializer def get(self, request, *args, **kwargs): token = request.data.get("token", "") if not token: """ do some action here """ if not UserAccess.objects.filter(accessToken=token).exists(): """ do some action here """ else: """ do some action here """ I want to pass the token in the headers like that : can anyone help me with this issue, thanks a lot in advance. -
How to copy a derived model instance in Django?
What is the right way to make a copy of a derived model (full copy including the base model)? class Item(models.Model): uid = models.AutoField(primary_key=True, editable=False) f = models.BooleanField(default=False) class Derived(Item): pass The following does not work: derived = Derived.objects.create() derived.pk = None derived.save() Related bug report: https://code.djangoproject.com/ticket/29871 -
How to make models in django which have different models as table columns which are specified upon different conditions?
I am new to django development and am stuck in a project that I am working on. I have been trying to create a website where multiple people can rent different furniture items for their houses, for a specified booking period, which can not overlap for someone else. Thus, I thought, I would create a furniture model and a booking period with a many to many relationship as shown below class booking_period(models.Model): booking_period_start = models.DateField(auto_now=False) booking_period_end = models.DateField(auto_now=False) booking_person_name = models.CharField(max_length=200) class Furniture(models.Model): furniture_type = models.CharField(max_length=200) furniture_owner_name = models.CharField(max_length=200) furniture_booking = models.ManyToManyField(booking_period) def __str__(self): return self.furniture_type Then in django admin, I added the furniture class so that we can add the models ourselves. The challenge is that a particular furniture can have multiple booking periods and they cannot overlap with each other. So, a furniture can have no booking period while other can have 5 or 10 booking periods. Also, different furniture items can have slightly different booking periods as well. So, if we add all the possible booking periods in the table booking period, it will end up taking a lot of space. It will be really helpful if someone could tell me the best way to do this, … -
access Django model in jQuery
I'm currently working on an app in which I want to automatically select the elements of two dropdown lists on selection of an element of another dropdown list : screnshot here so if I select job 3, I'd like to automatically select qualification 3, and coefficient 3 I have this model to store the values that I want to change : class JobModel(models.Model): job = models.CharField(max_length=50) qualification = models.ForeignKey(Qualification, default=1, on_delete=models.DO_NOTHING) coefficient = models.ForeignKey(Coefficient, default=1, on_delete=models.DO_NOTHING) and this form : <form action="" method="post"> {% csrf_token%} <table class="table table-responsive table-bordered "> <thead class="thead"> <tr> <th> REF</th> <th> poste</th> <th > nb </th> <th>{{ form.date_debut.label }}</th> <th>{{ form.date_fin.label }}</th> </tr> </thead> <tbody> <tr> <td>{{ form.poste_travail | add_class:'form_big'}} </td> <td>{{ form.metier_repere }}{{ form.qualification }} {{ form.coefficient }}</td> <td>{{ form.effectif | add_class:'form_small'}}</td> <td>{{ form.date_debut | add_class:'form_big'}}</td> <td>{{ form.date_fin | add_class:'form_big'}}</td> </tr> </table> <input type="submit" value="calculer"> </form> I found out that I needed tu use jQuery to achieve that but I don't know the first thing about it, so if anyone encountered a similar issue, or could help it would be super nice ! -
How class variable behaves during flask application execution? Are they shared between different HTTP request?
We have a parent class and two child class. To understand better we can say it Logger class which is responsible for logging. It extends to RequestLogger and ResponseLogger. class Logger: unique_id = None class RequestLogger(Logger): def __init__(self): Logger.unique_id = DB_RETURNED_ID class RequestLogger(Logger): def __init__(self): Log_request_with(self.unique_id) #Below lines are in route file. app.py RequestLogger() ResponseLogger() For each request the unique_id should be same, just to identify corresponding request and response. I decided to make a class variable unique_id in the parent class Logger. Whenever a request comes, the child RequestLogger class is called to log the request and the id that returned from database is set as class variable of its parent class i.e Logger.unique_id=returned_id Now at the time of sending back the response to user, we instantiate a ResponseLogger class which automatically gets the unique_id value from its parent class and logs into db with that id. What will happen if multiple requests comes to flask at the same time? How static variable will be shared? If it coincides with eachother, what should be appoach to keep them separate? -
Querying Django model when max_allowed_packet in MySQL is exceeded
So I've got this periodic task of sending an automated report to the user every month. The problem I encountered while generating the report data was that the MySQL DB has tons of report data for each user, so when I try to query on the User model, I get OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes"). I've gone into the dbshell and check what the setting for that variable is, and it's the max allowed value (1 GB). So I'm basically stuck here. Is there any way to get all the data without hitting that OperationalError? -
Django - combining two models serializer into one JSON response
I have two models List and Card. I'm trying to combine these two and make a single JSON response My List JSON response [ { "id": 1, "name": "List of things to do" }, { "id": 2, "name": "one more" } ] My Card JSON response [ { "id": 1, "title": "My first scrum card", "description": "list things todo here", "story_points": null, "business_value": null, "list": 1 }, { "id": 2, "title": "File my taxes", "description": "fill it before 1st of nov", "story_points": null, "business_value": null, "list": 1 }, ] My serializers.py file from rest_framework import serializers from .models import List, Card class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = '__all__' class ListSerializer(serializers.ModelSerializer): cards = CardSerializer(read_only=True, many=True) class Meta: model = List fields ='__all__' My api.py file from rest_framework.viewsets import ModelViewSet from .models import List, Card from .serializers import ListSerializer, CardSerializer class ListViewSet(ModelViewSet): queryset = List.objects.all() serializer_class = ListSerializer class CardViewSet(ModelViewSet): queryset = Card.objects.all() serializer_class = CardSerializer How can i achieve something like below in My List JSON response ? [ { "id": 1, "cards":[ { "id": 1, "title": "My first scrum card", "description": "list things todo here", "story_points": null, "business_value": null, "list": 1 }], "name": "List of things to … -
Regex validator on form seems to interfere with max_length validation on Charfield
I'm trying to validate input for a form field as a numbers only with 12-14 digits and which may have leading zeros. However when I add the below regex validator for numbers to my form field it seems to interfere whenever there is a max_length set on the form and it fails validation. only_numbers = RegexValidator(r'^\d{1,10}$') mpan_lower = forms.CharField(label='some_label', help_text=mark_safe('Help text with link. ' '<a href="#"> Need more help?</a>'), validators=[ only_numbers, ], max_length=14, ) -
Django custom login form only works on local
So I extended Django's AuthenticationForm to add placeholders and custom CSS classes for the login form like so: class CustomAuthForm(AuthenticationForm): username = forms.CharField(widget=TextInput(attrs={'class': 'validate login-input-box', 'placeholder': 'Username'})) password = forms.CharField(widget=PasswordInput(attrs={'class': 'login-input-box', 'placeholder': 'Password'})) And in my urls.py: path(r'^login/?$', auth_views.login, {'template_name': 'login.html', 'authentication_form': CustomAuthForm}), Which I thought was completely fine, given that it worked on local. I noticed today however that on the live site, neither the placeholders nor the classes showed up on the form. I did inspect element to confirm they were missing, and I tried on different browsers, as well as doing a hard reload of the page, all to no avail. Does anyone know why this would be failing only on the live site? It's being deployed to AWS elastic beanstalk. -
Django : Create a dynamic path with BASE_DIR
I have a very simple question but I don't understand why it doesn't work. I would like to set the path to .json file like this : with open(settings.BASE_DIR + '../../package.json') as package_json_file: But i'm getting this issue : FileNotFoundError: [Errno 2] No such file or directory: '/home/val/Bureau/Projets/OMCL/omcl/src../../package.json' How I can define the path from BASE_DIR and come back to .json file ? -
Django 2.0: UpdateView creates a new object instead of updating
For some reason my UpdateView is creating new objects instead of updating existing ones. I've tried changing the URL parameter from slug to pk to no avail. models.py class EarthScienceEvents(models.Model): slug = models.SlugField("Slug", primary_key=True) name = models.CharField("Name", max_length=200) forms.py class EarthScienceEventForm(forms.ModelForm): class Meta: model = EarthScienceEvents fields = ['name'] urls.py urlpatterns = [ path("update/<slug:pk>", views.EarthScienceEventsUpdateView.as_view(), name="update"), ] views.py class EarthScienceEventsUpdateView(UpdateView): model = EarthScienceEvents form_class = EarthScienceEventForm template_name = "earth_science_events/create_update.html" success_url = reverse_lazy('earth_science_events:list') create_update.html <form action="" method='POST'> {% csrf_token %} {{ form | crispy }} <button type="submit">Update</button> </form> What could be the issue here? -
python django, How to prohibit go to the next code from for loop
CODE: def redirectTest(item): try: headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } r = None try: r = requests.head(item, allow_redirects=False, headers=headers) except Exception as e: print(e) if r is not None: if r.status_code == 301: print("Tested: " + str(r.status_code)) elif r.status_code == 302: print("Tested: " + str(r.status_code)) else: print("Tested: " + str(r.status_code)) except requests.exceptions.RequestException as e: print('error: ' + e) return @ensure_csrf_cookie def re_check_url(request): if request.method == "POST": if request.is_ajax(): resolved_urls = ['twitch.tv/yumyumyu77'] scheme_list = ['http://www.', 'http://', 'https://www.', 'https://'] for item in resolved_urls: for scheme_item in scheme_list: redirectTest(scheme_item + item) return JsonResponse({'res': 1}) return JsonResponse({'res': 2}) This code is to check scheme + some url's responses. But when I execute that code, my django terminal print it: r_status_code: 301 r_status_code: 301 r_status_code: 200 [22/Oct/2018 23:54:49] "POST /re/check/url/ HTTP/1.1" 200 10 r_status_code: 301 Problem: I think it means that return JsonResponse({'res': 1}) this line is ahead, and print("Tested: " + str(r.status_code)) this line is after or later. Sometimes It print ordinarily, but sometimes it print abnormally. Question: I learned that python codes are executed by lines from top to bottom, but It seems not likely doing as I learned. Why this … -
how to find first image in a list of images in django
I have a Django template render result and images for search of cars. as follow: {% for item in result %} <li class="result-row"> <!-- image box --> <span> <a href="#" class="result-image-act" > {% for image in item.images_cars_set.all %} {% if image.car_images_exists %} {% if image.car_images.0 %} <img class="active" src=" {{image.car_images.url}}"> {% endif %} {% if not image.car_images.0 %} <img src=" {{image.car_images.url}}"> {% endif%} {% endif %} {% empty %} <img src="{% static 'path/to/default image' %}" class="active"> {% endfor %} </a> <span class="embed-result-price">{{item.price}}</span> <div class="swipe-wrap"> <div class="swipe-wrap-lef"> <span class="move" > <div class="swipe-prev"> <p>&lt;</p> </div> </span> </div> <div class="swipe-wrap-rig"> <span class="move" > <div class="swipe-next"> <p>&gt;</p> </div> </span> </div> </div> </span> The code is working fine except that I want to find the first image and put it in different img tag where it will take class="active". This class is used in javascript code to swipe all images to left or right. I tried to use {% if image.car_images.0 %} and {% if image.car_images.first %} to find first image but not success. what I get is all images without class of active. any help or suggestion. -
Changing selection Manytomany field in Django
I have a ManyToManyField named alphabet, which contains fields A, B, C and D - whether selected or unselected. How would it be possible to change queries that have selected letter 'A' into 'B'? class Alphabet(models.Model): id = models.AutoField(primary_key=True) letter = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.letter class Chapter(models.Model): letter = models.ManyToManyField(Alphabet, blank=True) class Section(models.Model): def somefunction: jobs = Chapter.objects.filter(letter__letter='A') for i in jobs: #change those selected with A to B -
Django 2.1.2 Password reset auth view: Reverse for 'password_reset_confirm' not found
I am having a problem with the passeord reset system. The code is as below. When I enter the respective URL into the browser address directly it shows the expected Django forms/pages. However if I fill an email address and hit enter/click the link, I get the "Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name." error at line 6 in password_reset_email.html. But I have included the uid64! and the token! Also, when I deliberately use an incorrect email address I get the "Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name." error. I cannot see from the django documentation, other similar questions on this site, or various guides, what the obvious simple step is that I must have missed. from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'users' urlpatterns = [ path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset/complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ]