Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django creates new default permissions even with default_permissions=() in the Meta?
I setup some test app to check django's behaviour. Makefile for testing: clean: rm db.sqlite3 mig_model: python manage.py migrate flights 0001 mig_all: python manage.py migrate show1 show2: python manage.py shell -c "from django.contrib.auth.models import Permission; print(list(Permission.objects.values_list('id', 'codename')))" all: clean mig_model show1 mig_all show2 removing old db migrating to the point when first own model is created after migration default permissions should be created in post_migrate signal. But I specify in Model.Meta that no default permissions should be created check all permissions - I can see that they were indeed generated migrate everything else, which is just 1 more data-migration where I delete all permissions in the system show all permissions again and I can see that old permission were deleted and new ones created after migration (they all have new ids) models.py: class Schedule(models.Model): flight_day = models.DateField() class Meta: default_permissions = () permissions = () -
How to hide a list element in html
I want to hide a list element when I click on a button. I tried it with in Javascript. This does not work. document.getElementById("1").children[0].style.display = "none" <script> function hid(){ document.getElementById("1").children[0].style.display = "none" } </script> <div class="container-fluid"> <div class="column"> <div class="col-md-2 "> <ul class="list-group" id="1"> <li id="2"><a href="{% url 'search:barbars' %}" class="list-group-item list-group-item-action">barbar <div class="image-parent"> <img src="http://cool-web.de/icons/images/024800/024768.ico" class="img-fluid" alt="nothing"> </div> <!-- The Button --> <button onclick="hid" class="btn btn-outline-success my2 my-sm-0" type="submit">Search</button> -
Define python directory in cpanel
My Cpanel host has 2 instances of Python. Python 2.6 - /usr/bin/python Python 3.6 - /usr/bin/python3.6 If I run this script: #! /usr/bin/python print "Content-type: text/html\n\n" print "<html>Hello world!</html>" It works! But If it doesn't work (Internal error 500) if I run: #! /usr/bin/python3.6 print "Content-type: text/html\n\n" print "<html>Hello world!</html>" I know python 3.6 is installed and in the specified path, as you can see below: Thanks. -
Django annotate(...) taking a dictionary
I have somewhat complex django query with a lot of .annotate: query = ModuleEngagement.objects.filter(course_id=course_id)\ .values('username')\ .annotate( videos_overall=Sum(Case(When(entity_type='video', then='count'), output_field=IntegerField()))) \ .annotate( videos_last_week=Sum(Case(When(entity_type='video', created__gt=seven_days_ago, then=1), output_field=IntegerField()))) \ .annotate( problems_overall=Sum(Case(When(entity_type='problem', then='count'), output_field=IntegerField()))) \ .annotate( problems_last_week=Sum(Case(When(entity_type='problem', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( correct_problems_overall=Sum(Case(When(entity_type='problem', event='completed', then='count'), output_field=IntegerField()))) \ .annotate( correct_problems_last_week=Sum(Case(When(entity_type='problem', event='completed', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( problems_attempts_overall=Sum(Case(When(entity_type='problem', event='attempted', then='count'), output_field=IntegerField()))) \ .annotate( problems_attempts_last_week=Sum(Case(When(entity_type='problem', event='attempted', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( forum_posts_overall=Sum(Case(When(entity_type='discussion', then='count'), output_field=IntegerField()))) \ .annotate( forum_posts_last_week=Sum(Case(When(entity_type='discussion', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( date_last_active=Max('created')) Does annotate accept a dictionary as a parameter so I can move all the annotates into it? If so, what would be the syntax? -
Celery task.status method rises a exception : AttributeError: module <module_name> has no attribute 'DoesNotExist'
Stack: django = "==2.2.2" django-celery-beat = "==1.4.0" celery = "==v4.3.0rc1" python_version = "3.7" I have a class that import some data from csv/xls file and save da data, here is my celery config: CELERY_TASK_ALWAYS_EAGER = False CELERY_BROKER_URL = config('REDIS_BROKER_URL') CELERY_RESULT_BACKEND = config('REDIS_RESULT_URL') CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Here is where i call my task (some class based view): def form_valid(self, form): if self.request.is_ajax(): form.save() instance = form.save() kwargs = { 'corporation_id': self.corporation.id, 'file_id': instance.id, } task_id = import_file_task.apply_async( kwargs=kwargs, ) instance.tas_id = task_id instance.save() return JsonResponse( { 'form_status': 'Success', 'task_id': str(task_id), } ) return super().form_valid(form) Here is where i call my task: @celery_app.task(bind=True) def import_file_task(_, corporation_id, file_id): sale_file = SaleFile.objects.get( id=file_id, corporation_id=corporation_id, ) if sale_file.type == PRODUCT_FILE: error = ProductImporter( corporation_id=corporation_id, file_id=file_id, product_file=sale_file, ).save() elif sale_file.type == RECEIVABLE_FILE: error = ReceivableImporter( corporation_id=corporation_id, file_id=file_id, receivable_file=sale_file, ).save() else: raise ValueError('File type is not valid') task = AsyncResult(sale_file.tas_id) task.info = error task.status = 'COMPLETED' Here is where i try to poll the task status and i get the error! class TaskStatus(View): def get(self, request): task_id = request.GET.get('_task_id') task = AsyncResult(task_id) print(task) print(task.state) #HERE IS THE ERROR print(dir(task)) #THE STATUS APPEAR HERE success_response = ( { 'status': ['state: ' ], … -
Adding the class name to the selection options. Django - forms
I have a very simple forms.py PROVINCE_CHOCIES = [ (1, 'New York'), (2, 'Las Vegas'), (3, 'San Francisco'), ] class SearchForm(forms.Form): province = forms.ChoiceField(choices=PROVINCE_CHOCIES) Is it possible to add a class to the drop-down list? My form in htmlu looks like this: <option value="1">New York</option> <option value="2">Las Vegas</option> <option value="3">San Francisco</option> The expected result is: <option value="1" class="A">New York</option> <option value="2" class="A">Las Vegas</option> <option value="3" class="D">San Francisco</option If possible? how can I do this in my forms.py file, or using some external plug? The solution will be useful for me to use the simple dependent/chained drop-down list. As in this exampe. Any help will be appreciated. -
Convert context into serialize data
I have a function in django app which I want to convert into serializer data to use it in react via API. class DispatchHistory(ListView): model = DispatchPlan context_object_name = 'plan' template_name = 'classroom/teachers/dispatcher_history.html' def get_queryset (self): return DispatchPlan.objects.filter(owner_id=self.request.user.pk) def get_context_data (self, **kwargs): context = super().get_context_data(**kwargs) dispatch_plans = DispatchPlan.objects.filter(owner_id=self.request.user.pk) dis_items = [] for i in dispatch_plans: it = i.items obj_list = [] for j in it: obj = get_object_or_404(ItemBatch, id=j) obj_list.append(obj) dis_items.append(obj_list) context['t_items'] = dispatch_plans context["ttt"] = dis_items return context I created a Serializer for this: class dispatchhistorySerializer(serializers.ModelSerializer): class Meta: model = DispatchPlan fields = "__all__" and tried this: class DispatchHistoryAPI(APIView): serializer_class = dispatchhistorySerializer def get(self, request, **kwargs): try: dispatch_plans = DispatchPlan.objects.filter(owner_id=request.user.pk) context = {} dis_items = [] for i in dispatch_plans: it = i.items obj_list = [] for j in it: obj = self.serializer_class(get_object_or_404(ItemBatch, id=j)).data obj_list.append(obj) dis_items.append(obj_list) context['t_items'] = dispatch_plans context["ttt"] = dis_items #what comes here ? return JsonResponse({ "details": context }) except: raise return JsonResponse({ "details": "Failed " }, status=500) How do I use this serializer to convert the context data to serializer data to use it in an API? -
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; # …