Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx configuration: IP address showing instead of domain name
I put my website on a DigitalOcean Droplet and it worked. I called the IP address and it showed me the address, then I forwarded the domain to the website IP and it connected it. The issue at the beginning was that when I was accessing the website with my domain the access bar was showing my domain and when the page loaded it showed the IP address instead of the domain. it seemed that the issue was in my nginx configuration, as I wrote just my IP address there. ``` server { listen 80; server_name 178.128.42.100; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/patrik_website/patrik_web/form/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } ``` I updated the file changing the server_name variable to: server_name patrikmuniak.com www.patrikmuniak.com; the lists in settings.py-ALLOWED_HOSTS=['*'] and after the update to the nginx website configuration, this it's been restarted with: sudo systemctl restart nginx the output is that when I use any browser and type the IP or the domain, now it shows me the page with 'Welcome to nginx!'. if you need more info please let me know. P.S. the OS is Ubuntu 19.04 -
Django/Wagtail: Inherit the fields defined in another form page
We are currently working on a Wagtail project which needs us to have two different forms (AbstractEmailForm) with the same user-defined form fields (AbstractFormField). More precisely, the user defines a form page which fields musst be filled out with short keywords in the frontend. Afterwards, another form page is accepting longer texts which are based on these keywords. Therefore, this second page is using fields named the same as the first keyword form page fields. We already tried to solve this problem for a few hours now and we came to the conclusion that this has likely to be done by getting the form fields out of the instance of the first form page, but I could not yet figure out how this is done. Propably by defining a OneToOneField, but I have no idea on how to get data out of this, I feel like I tried everything. -
How to implement shallow delete in Django
I really like the concept of shallow delete - when you delete a record it only sets it's deleted field to true but stays in a database. To remove it from the database, you have to delete it "forcefully", e.g. by setting some flag to true. The app then should always filter the deleted records, so they won't appear anywhere and they just seem like they are not in the db. This is what I came up with and works pretty well. class BaseManager(Manager): def get_queryset(self): qs = super().get_queryset() qs = qs.filter(deleted=1) return qs def all_objects(self): return super().get_queryset() class BaseModel(models.Model): deleted = models.IntegerField(default=0) ... objects = BaseManager() def delete(self, from_db=False, using=None, keep_parents=False): if from_db: super(BaseModel, self).delete(using, keep_parents) return self.deleted = 1 self.save() The problem is, that I have no idea, how to filter it on other places, lets say on related collections, many to many relationships or in queries, when the model is used for condition. E.g. I have device called "Car" related to User. User.objects.get(device__name="Car") would return that user. When I shallowly delete the device (aka set deleted = true) and try to filter User.objects.get(device__name="Car"), I would like to get an empty result. Another thing is that when a … -
How to request a verification pin on form submission
I'm new to django and im trying to create a webapp where the user submit a form in the form of a transaction but will be required to input a verification pin before the transaction will be committed to a database. Just want to know if there's any built in function or python package that caters for this, I have tried to implemented it in the view but its not working because I've not been able to call another form from that view which contains a form already. Any suggestion or push in the right direction will be really appreciated as I've banged my head over this for a couple of days now -
How to redirect different page by user's type
I want to make some kind of community separated by user's type(eg. univ, department) main login page is same for every user. when user login, they should be redirect to their community. every community works on same django code. Problem comes here. i make User model have univ field. and make view.py to filter post query by user's univ field. but i think this is not a perfect way to separate community by univ. Can you suggest me more better way? -
Requests with dots at the end gives bad request 400
This is my configuration if I visit https://www.example.com. the dot at the end does not work # the upstream component nginx needs to connect to upstream django { server unix:///tmp/example.sock; # for a file socket } # Redirect server { listen 80; listen 443 ssl; ssl_certificate /etc/nginx/ssl/ssl-bundle.crt; ssl_certificate_key /etc/nginx/ssl/example.key; rewrite ^(.*) $scheme://www.example.com$1 permanent; } # SSL Request server { listen 443; server_name www.example.com; root /var/www/example; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste ssl on; ssl_certificate /etc/nginx/ssl/ssl-bundle.crt; ssl_certificate_key /etc/nginx/ssl/example.key; ssl_protocols TLSv1.2 TLSv1.1; # Django media location /uploads { alias /var/www/example/uploads; # your Django project's media files - amend as required expires 7d; } location /static { alias /var/www/example/static; # your Django project's static files - amend as required expires 7d; } location /favicon.ico { alias /var/www/example/static/img/favicon.ico; # your Django project's static files - amend as required } location /robots.txt { alias /var/www/example/robots.txt; # robots.txt } location /ntat { uwsgi_pass django; include uwsgi_params; } location / { rewrite ^(.*) http//www.example.com$1; } } # Normal Request server { # the port your site will be served on listen 80; # the domain name it will serve for server_name www.example.com charset utf-8; # max upload size client_max_body_size 75M; # … -
How can I use a range slider with django-filter?
How to use a range slider (for example the jQuery one) with django-filter package? So now I'm using the RangeFilter which just displays to normal text fields for the range. So the search function is working perfectly fin but it's just not that fancy as a cool slider. class TentFilter(django_filters.FilterSet): width = django_filters.NumberFilter(label="Breite") length = django_filters.NumberFilter(label="Länge") number_of_People = RangeFilter(label="People range") class Meta: model = Tent fields = ['width', 'length', 'number_of_People', ] I really would appreciate help because this thing is stressing me out. -
QuerySet Optimisations in Django
I was just wondering, I have the following two pseudo-related queries: organisation = Organisation.objects.get(pk=org_id) employees = Employee.objects.filter(organisation=organisation).filter(is_active=True) Each Employee has a ForeignKey relationship with Organisation. I was wondering if there is anything I can leverage to do the above in one Query in the native Django ORM? Also, would: employees = Employee.objects.filter(organisation__id=organisation.id).filter(is_active=True) Be a quicker way to fetch employees? -
Filtering objects by timezone aware dates
Let's say I have TIME_ZONE variable in settings set to 'Europe/Prague' and also USE_TZ set to True. I also have some data stored in Example: id timestamp 1 2012-07-27T00:00:00+02:00 2 2018-03-11T02:00:00+01:00 3 2013-11-04T14:08:40+01:00 This is what I'm trying to achieve: Extract all dates from those data Filter those data date by date and perform some other action on them For extracting dates I use either Example.dates('timestamp', 'day') or Example.annotate(date=TruncDay('timestamp')).values('date'). Now here is the difference: for first object from example above (with timestamp=2012-07-27T00:00:00+02:00), date return by first approach is 2012-07-27, whereas for second approach it is 2012-07-26. I would like filter to be timezone aware, so I'm currently sticking with the first one. For filtering I am using Example.filter(timestamp__date=date). And there's a problem - it seems that __date filters by date in UTC. For date 2012-07-27 it returns empty QuerySet and for 2012-07-26 it returns first object. Is there any way to achieve filter by timezone aware date? -
dynamically condition form fields in django(Display fields based on previous fields value)
I am currently working on a django project .I have 2 fields namely has_conducted(Radio button[yes and no options]) and years(checkbox) fields.My main idea is that when I click yes in has_conducted the years field must be visible and if no is selected the years field must be disabled or hidden.Plzz do help me solve this .Thanks in advance models.py YES_NO = ( ('Y','Yes'), ('N','No') ) YR_REVISION = ( ('13-14','2013-2014'), ('14-15','2014-2015'), ('15-16','2015-2016'), ('16-17','2016-2017'), ('17-18','2017-2018'), ('18-19','2018-2019'), ('19-20','2019-2020'), ) class SurveyForm(models.Model): has_conducted = models.CharField(choices=YES_NO,max_length=20) year = MultiSelectField(choices=YR_REVISION,null=True,blank=True) forms.py YES_NO = ( ('Y','Yes'), ('N','No') ) class SurveyForm(forms.ModelForm): has_conducted =forms.ChoiceField(choices=YES_NO,widget=forms.RadioSelect()) class Meta: model = SurveyForm fields = '__all__' form.html <div class="container content"> <form method = "POST"> {% csrf_token %} {{ form|crispy }} <button class="btn-warning text-dark btn" type="submit">Submit</input> </form> </div> ````[enter image description here][1] [1]: https://i.stack.imgur.com/Ps8ea.png -
How to add tags name for makemessages, parse tag as xgettext
I'm creating translation for my site. Sometimes I need to add field in django.po when I use custom simple_tag. I expect to see following: {% my_not_standard_trans 'Value' %} I need to use makemessages for parse my custom tag like 'trans'. I tried use _noop, but it not works like {% some_tag _("Page not found") %} I have created custom makemessages command with string xgettext_options = makemessages.Command.xgettext_options + ['--keyword=_noop'] but it works for .py files only, if I add ['--keyword=custom_tag'] it not work also -
Setting up media file access on AWS S3
Im using boto3 and django-storage libraries for apload media files of my django project. storage_backends.py class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_STORAGE_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False class PublicStaticStorage(S3Boto3Storage): location = settings.AWS_PUBLIC_STATIC_LOCATION settings.py AWS_STORAGE_LOCATION = 'media/private' AWS_PUBLIC_STATIC_LOCATION = 'static/' models.py class Documents(models.Model): """ uploaded documents""" author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) upload = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=255, blank=True, null=True) datafile = models.FileField() created = models.DateTimeField(auto_now_add=True) type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) File loading works well. But there is a point I don't understand, and the link to the file looks wrong (it contains static instead of media). Looks like https://myhost.s3.amazonaws.com/static/class-descriptions_1.csv And else about access. Now that I click on the link to the file, I get a message <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>4B8296F8F77491F5</RequestId> <HostId> CG96q+LGWcvsIK2YkuaE2wExL8/YTqH1PmjOSFGAqcgaKaTYnOet1QoItGJhW1Oj </HostId> </Error> This is normal for unregistered users, but how do I allow users registered in my Django project to see this file? -
How to return ManytoManyField to string?
I want to return the ManyToManyField as a string but it turned out to be none. This is the result "Cart id: 36,whitet-shirt,products.Variation.None" I got carts.models.py class CartItem(models.Model): cart = models.ForeignKey(Cart,null=True,blank=True,on_delete=models.DO_NOTHING) product = models.ForeignKey(Product_info,null=True,blank=True,on_delete=models.SET_NULL) variations = models.ManyToManyField(Variation,null=True,blank=True) quantity = models.IntegerField(default=1) linetotal = models.DecimalField(max_digits=100,default=10.99,decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False,null=True,blank=True) updated = models.DateTimeField(auto_now_add=False,auto_now=True,null=True,blank=True) def __str__(self): return "{},{},{}".format(self.cart,self.product,self.variations) products/models.py class Variation(models.Model): product = models.ForeignKey(Product_info,null=True,on_delete=models.SET_NULL) cat = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=100) price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) description = models.TextField(null=True,blank=True) active = models.BooleanField(default=True) objects = VariationManager() def __str__(self): return self.title -
Download link from ForeignKey model
I would like to create an attachment on every post of my blog. Then I've do this: class FileUpload(models.Model): name = models.Charfield(max_length=70) file = models.FileField() def __str__(self): return self.name def get_absolute_url(self): return reverse("single_file", kwargs={"pk": self.pk}) class BlogPost(models.Model): title = models.Charfield(max_length=70) . . . attachment = models.ForeignKey( FileUpload, on_delete=models.CASCADE, related_name="related_attachment", null=True, blank=True, ) Inside the template of a single post I've put this: {% if blogpost.attachment %} <hr> <div> <a class="btn btn-info" href="{{ attachment.get_absolute_url }}" rule="button"> Download </a> </div> {% endif %} But I see that the href is empty and I can't download the attachment. The if condition work fine because the button didn't appear if the post don't have the attachment. What is the right way to put a download link inside my download button? -
Django Admin multiple inline validation upon submit
I'm trying to validate 2 inlines upon submit. The validation is a qty cannot be 0 if both inlines are zero and will allow if 1 of the qtys is greater than 1. Any suggestions on how to capture both form values upon submit and flag a validation error based on the logic above? Code Flow class AInlineForm(forms.ModelForm): qty = forms.IntegerField(min_value=0) class Meta: model = A exclude = ['created'] def __init__(self, *args, **kwargs): super(AInlineForm, self).__init__(*args, **kwargs) self.fields['qty'].initial = 0 class BInlineForm(forms.ModelForm): qty = forms.IntegerField(min_value=0) class Meta: model = B exclude = ['created'] def __init__(self, *args, **kwargs): super(BInlineForm, self).__init__(*args, **kwargs) self.fields['qty'].initial = 0 class BInline(admin.TabularInline): model = B extra = 1 max_num = 1 form = BInlineForm class AInline(admin.TabularInline): model = A extra = 1 max_num = 1 form = AInlineForm class OrderAdmin(admin.ModelAdmin): inlines = [AInline, BInline] -
Data not showing on template
This is the first time I'll be implementing a Class Based View on a real project but the data is not showing on the template. <div class="container"> <h4 class="heading-decorated text-center mt-5">Our Volunteers</h4> {% for volunteer in volunteers %} <div class="row row-30 text-center mb-5"> <div class="col-sm-6 col-md-3"> <figure class="box-icon-image"><a href="#"><img class="rounded" src="{{volunteer.volunteer_image.url}}" alt="" width="126" height="102"/></a></figure> <p class="lead">{{volunteers.volunteer_name}}</p> </div> </div> {% endfor %} </div> views.py class VolunteerListView(ListView): model = Volunteers context_object_name = 'volunteer' template_name = 'add_my_language/home.html' models.py class Volunteers(models.Model): volunteer_image = models.ImageField(upload_to='media/volunteers') volunteer_name = models.CharField(max_length=255, blank=False) def __str__(self): return self.volunteer_name Did I miss anything? -
Django adds https:// in all my static files. This is after integrating S3
After integrating s3 and adding my static url all my static files add a http:// in the url <link rel="stylesheet" href="https://http://bucket_name.s3.amazonaws.com/static/css/styles.css"> STATIC_URL='https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) -
AJAX request to a Django server stays on stalled Chrome
I have a simple django server with the Django Rest API installed. My problem is that when I make a simple query using AJAX the query stays stalled by Chrome: If I make this request disabling Chrome's cache (with the dev tools options) it loads without any problem. Here is the ajax query I use: $.ajax({ type:"GET", dataType:"json", beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Token '+global_api_token);}, url:url, error: function(result) { console.log(result) }, success: function(result){ console.log(result) } }); Does any know why this is happening? -
Django formset errorlist 'This field is required'
I am creating a formset with django which contains children information. I am using createview (CBV) for this. The form is displayed properly, it has functionality of adding children and removing children all working properly. But, when i click on submit, form_invalid is called instead of form_valid. To know this issue i printed form.errors and i saw following errors <ul class="errorlist"><li>deal_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>son_or_daugher<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_age<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_education<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_occupation<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Below is my code Template :- {% extends "forms_app/base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} <h2>Profile</h2> <hr> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} <table class="table"> {{ childrens.management_form }} {% for form in childrens.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} … -
Get not all values but specific values of field in another model with one to one field
I have two models. 1. courses 2. First Year Here is course Model class Courses(models.Model): class Meta: verbose_name_plural = 'Courses' year_choices = [ ('----', '----'), ('First Year', 'First Year'), ('Second Year', 'Second Year'), ('Third Year', 'Third Year'), ('Fourth Year', 'Fourth Year'), ('Minor', 'Minor'), ] year = models.CharField(max_length=50,default='----',choices=year_choices) course_code = models.CharField(max_length=10, default='', validators=[MinLengthValidator(1)]) Here is FirstYear Model class FirstYear(models.Model): class Meta: verbose_name_plural = '1. First Year' course = models.OneToOneField(Courses, default='', on_delete=models.CASCADE) title = models.CharField(max_length=100,default='') def __str__(self): return '{}'.format(self.title).capitalize() I'm new to Django. When I run this code all of the course code is returning. But I don't need that. My question is I have to invoke the course_code field only if it is first year and not all year. Please help me here. Thank you. -
Django 2.2 set ModelChoiceField initial value without id/pk
I have a GET based search, passing a few search terms and paging info through the query string. I can grab the items from the query string without any issues, but passing them back to the template via the SearchForm to preserve the search is proving to be difficult. items/?search=foo&category=bar&page=1&pageSize=20 forms.py class SearchForm(forms.Form): search = forms.CharField(*) category = forms.ModelChoiceField(queryset=Items.objects.all(), *) *simplified for brevity In the view, I can retrieve all the values or their defaults from the query string, and I can even set the value for the search field, but the ModelChoiceField is the one I am struggling with. I can set an initial value, but not based on the select text... views.py class ItemList(View): template_name = 'items.html' def get(self, request): items = Item.objects.all() form = SearchForm() search = request.GET.get('search') category = request.GET.get('category') page = int(request.GET.get('page', 1)) pageSize = int(request.GET.get('pageSize', 20)) if category != None: #non working: #form.fields['category'].initial = category #working by setting a value form.fields['category'].initial = 1 items.filter(category__name=category) if search != None: form.initial['search'] = search items = items.filter(field__icontains=search) context = { 'form': form, 'items': items } return render(request, self.template_name, context) I tried various methods of trying to retrieve the value/id from the form.category field unsuccessfully. I would hate … -
How to publish django web to local server?
I am now using django to develop a web page but I found that I have no idea to publish it. As I am a really new to web programming, I don't even know what the key words I should search for, but I am asked to write a web program and no one in the company can help me with this. I know in my company, the company website is publish on the local server with only the html files. Therefore, if I want to publish the whole django project, how can I do it? or where can I have those information to look for? My main goal is to publish it to the intranet and also can interact with other pages that were not developed by django. For example, in the nav bar, there will be one link to the webpage that designed by django. Thank you. -
python manage.py runserver command not working [duplicate]
This question already has an answer here: Django runserver error, new installation, first time user of Django 2 answers python manage.py runserver not working and showing errors that are shown in image: enter image description here Kindly suggest a solution -
Django: How to conditionally define fields in a model mixin?
In my back-end (API) site, there are certain fields that are common to most models, but not all. I have been using mixins for those fields so that I can include them for the models they apply to, and omit them from the ones they don't. For example: class AddressPhoneModelMixin(models.Model): address = models.TextField( verbose_name=_('Address'), blank=True, null=True, ) country = models.ForeignKey( Country, on_delete=models.SET_NULL, verbose_name=_('Country'), blank=True, null=True, ) phone_number = PhoneNumberField( verbose_name=_('Phone'), blank=True, null=True, ) mobile_number = PhoneNumberField( verbose_name=_('Mobile Phone'), blank=True, null=True, ) fax_number = PhoneNumberField( verbose_name=_('Fax'), blank=True, null=True, ) class Meta: abstract = True But I have other such mixins, and when a model needs to include all fields, the model definition gets to be quite long: class Client(AddressPhoneModelMixin, DateFieldsModelMixin, models.Model): And I now have other "common" fields I want to add, so it's only going to get worse. I want to keep all these common fields in one place for DRY, but also in case anything changes about a field, I only have one place to make the changes. My idea is to have one mixin called CommonFieldsModelMixin, so that I will have only one mixin to include in the model definition. But for those models that don't need certain … -
Specify aws named profile S3Boto3Storage
I am using S3Boto3Storage for uploading django images to s3. I have multiple profiles in my local. Can I specify profile name with S3Boto3Storage ?