Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a copy of a table before delete ( django pre_delete )
I'm new to Django so I guess my Question is basic but I need your help. I have a table called Answer. class Answer(models.Model): id = models.AutoField(auto_created=True,primary_key=True) sku = models.CharField(max_length=128, default=secrets.token_urlsafe(16), editable=False) user = models.ForeignKey(User,on_delete=models.SET_NULL, null= True) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL, null=True) content = models.TextField() created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) it's for a forum. Before a user deletes his/her answer, I want to make a copy of the answer. I want to make a new table that has the values of this table, for example, a table named DeletedAnswer that has all the values in Answer table. thanks -
Cancel impact of css from bootstrap4 (Chrome)
I added a bootstrap template to my Django project and I have a different element size compared to the source code. https://startbootstrap.com/previews/business-frontpage/ I found out that issue deals with h-100 Removed h-100 in dev tools I removed h-100 from .css file, but result is the same. How can I cancel impact of h-100 style ??? My code: https://github.com/mascai/datat_site -
I tried to run the command : "py manage.py runserver" but i's not working anymore,why?
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it I tried to run the command: py manage.py runserver but it gives the error mentioned above, the problem isn't only that, I've been using django for days and it was working fine until today -
masking port number django runsslserver in nginx
I have django project running in ngnix in port 4321. i am runing django project using runsslserver which is returning me https using below command python manage.py runsslserver --certificate /etc/nginx/ssl/XXXXXXX.pem --key /etc/nginx/ssl/XXXXXXX.key 0.0.0.0:4321 my website is ready when i run like https://mywebsite.com:4321 I want to show it as https://mywebsite.com/miniweb i have 2 files in /etc/nginx/sites-enabled which is default and ssl Tried below code and few others with many changes in ssl file but not working server { server_name mywebsite.com:4321; listen 443; # tried this because its in https return 301 https://mywebsite.com/miniweb$request_uri; } Please help me -
How to serve static files with Django via mod_wsgi and Apache on a windows server?
So I know this question has been asked a lot, but I have attempted every answer and still came to no solution. The problem is that static files are not found (404 error) when I open my website. (css files throw an Refused to apply style from 'example.com/static/css/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled., however I think this is due to the css not being found.) I am running Apache 2.4 on a windows 10, 64-bit server with python 3.7 installed. I installed django in a virtualenvironment using virtualenvwrapper-win. Here the httpd.conf: Define ALPHAROOT d:/django/alpha LoadFile "c:/users/truninger-admin/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/truninger-admin/envs/djangoenv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/truninger-admin/envs/djangoenv" WSGIScriptAlias / ${ALPHAROOT}/alpha/wsgi.py WSGIPythonPath ${ALPHAROOT} <VirtualHost *:80> ServerName alpha.truningerag.ch Alias /static/ d:/django/static/ <Directory d:/django/static> Require all granted </Directory> WSGIScriptAlias / ${ALPHAROOT}/alpha/wsgi.py <Directory d:/django/alpha/alpha> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> And the settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") And the wsgi.py: import os,sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'alpha.settings') application = get_wsgi_application() from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() The odd thing here is that if I comment out application = get_wsgi_application() the server raises an exception django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Things … -
Optimising API queries using JSONField()
Initial opening: I am utilising postgresql JSONFields. I have the following attribute (field) in my User model: class User(AbstractUser): ... benefits = JSONField(default=dict()) ... I essentially currently serialize benefits for each User on the front end with DRF: benefits = UserBenefit.objects.filter(user=self) serializer = UserBenefitSerializer(benefits, many=True) As the underlying returned benefits changes little and slowly, I thought about "caching" the JSON in the database every time there is a change to improve the performance of the UserBenefit.objects.filter(user=user) QuerySet. Instead, becoming user.benefits and hopefully lightening DB load over 100K+ users. 1st Q: Should I do this? 2nd Q: Is there an efficient way to write the corresponding serializer.data <class 'rest_framework.utils.serializer_helpers.ReturnList'> to the JSON field? -
django-crontab not executing django custom command
I am using django-corntab to execute my Django Commands after specific interval of time. I am having trouble while defining django settings for CORNJOBS. I read the doc of django-corntab and mentioned the path of my django command class but its not working. management/commands/send_email.py class Command(BaseCommand): def handle(self, *args, **kwargs): try: msg = EmailMessage('Hi! I am using Cron!', 'I am using django commands and cron for scheduled tasks.', to=['manju.negi14@gmail.com']) msg.send() self.stdout.write(self.style.SUCCESS('Successfully sent email')) except Exception: raise CommandError('Sorry! something went Wrong!') settings.py INSTALLED_APPS = [ .... # third party packages 'django_crontab', # local apps 'mynewapp',] CRONJOBS = [ ('*/1 * * * *', 'mynewapp.management.commands.send_email.Command', '>> '+os.path.join(BASE_DIR,'log/mylogfile.log 2>&1'))] -
How to have multiple integer or Charfields that belong to same formfield in django
I need to group 4 integer or charfields under a same form field like FORMFIELD: No of students in each year? INTEGERFIELDS: 2016-2017 2 INTEGERFIELDS: 2017-2018 4 INTEGERFIELDS: 2018-2019 3 INTEGERFIELDS: 2019-2020 5 I need only one main formfield and other fields must belong to the same category plzz help me writing the code in django .Thanks in advance -
Pass both name and dictionary via urls.py
I am trying to pass a value in a dictionary via a url. Django tells me I can do this via a 3rd parameter , but this seems to conflict with setting the name value for the link. I have this in my project urls.py at the moment, which it doesn't like at all (presumably because it has 4 parameters): urlpatterns += [re_path(r"^$", views.HomePageView.as_view(), name="homepage", {"display": "all"}] I'd also like to be able to pass {"display": "user"} in urls.py in one of the apps. The reason for this is so I can use the same list view, and just change the query to return either all records (which will be displayed most recent first in paginated list view on the homepage), or only those owned by the current logged in user (when they opt to view their records). I am thinking that in the list view I will interrogate this value and use it in get_queryset to determine which records I want. How can I pass both the name and the dictionary via the url? Or am I approaching this whole thing incorrectly? -
Displaying foreign key with DRF create api
Display Foreign Keys correctly I have 2 models in DRF: class Location(models.Model): country = models.CharField(max_length=50, null=False) city = models.CharField(max_length=50, null=False) currency = models.CharField(max_length=20, null=False) def save(self, *args, **kwargs): super(Location, self).save(*args, **kwargs) class Meta: unique_together = ('country', 'city', ) permissions = ( ('can_view', 'Can View'), ('can_modify', 'Can Modify'), ) def __str__(self): return (self.country + ":" + self.city) class Holiday(models.Model): country = models.ForeignKey(Location, related_name='location_country', on_delete='CASCADE') city = models.ForeignKey(Location, related_name='location_city', on_delete='CASCADE') holiday_date = models.DateField(auto_now=False, auto_now_add=False) def save(self, *args, **kwargs): super(Holiday, self).save(*args, **kwargs) def __str__(self): return (self.country + ":" + self.city + ":" + self.holiday_date) class Meta: unique_together = ('country', 'city', 'holiday_date') When trying to create a Holiday, for country and city field I get dropdown as below: country: country_name:city_name city: country_name:city_name I want to display these fields correctly so that country and city fields are displayed properly. I understand the current output is because of str definition in Location models and I need that to display the table fields in django admin. How can I overwrite these for the API only. Below is the create API I am using: class HolidayCreateView(generics.CreateAPIView): serializer_class = HolidayCreateSerializer def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) class HolidayCreateSerializer(serializers.ModelSerializer): class Meta: model = Holiday fields = ('id', … -
How should I make a model object remember the result of a field's pre_save?
I have a model Task and two calculated fields key and key_sort and a related field content_object. key should be copied from the related object: self.content_object.key key_sort should be a variant of the value in key (suitable for natural sorting, so A10 becomes a0010, but that's another story) I have implemented this using custom fields which override pre_save: class KeyField(CharField): def pre_save(self, model_instance, add): return model_instance.content_object.key class NatsortField(CharField): # ... def pre_save(self, model_instance, add): return natsort_str(getattr(model_instance, self.for_field)) class Task(Model): key = KeyField() key_sort = NatsortField(for_field='key') content_object = ForeignKey(Thing) When saving, the key field is saved correctly to the database, but the model instance is not updated, so in the pre_save for the key_sort field, the new value of key is not available. Thus the key_sort field will not be calculated correctly. Should we always update model_instance in pre_save? Should I have plain CharFields and do the calculations by overriding Model.save instead? -
How to keep a list of all active users of the web app?
I am new to Django. I have been trying a store a list of all active ip addresses which are using the web app currently. My approach is to add a new entry to the database table with the IP address of the user as soon as a person logs in. And keep updating the timestamp column (LastPingTime) in the table with the current time every 3 seconds or so. So the active ip addresses would be all the rows in the table whose LastPingTime is less than or equal to 3 seconds from the current time. But I don't know to go about it. Please help with this. How do I run a periodic function which does this for every new user? Thanks in advance. -
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