Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save text input from user without modifying property for admin?
I want to store the user's inputs in my database, and I don't wanna the admin can change those user's input. in my models.py, I have: class UserInput(): firs_name = models.CharField(max_length=10) as you can see, the CharField form field is gonna make a character field, so the admin can change the user input. I don't want that. -
Django Cassandra engine does not record datettime correctly
I am using django Cassandra engine for my project and I have defined this model: class StatusLog(DjangoCassandraModel): created_at = columns.DateTime(default=datetime.datetime.now()) but when I add record to database created_at is not recording correct time (for example for all the records of today it records 2019-06-19 11:30:34.154). I dont know where is the problem -
NoReverseMatch at / Reverse for 'single_product' with no arguments not found. 1 pattern(s) tried: ['products/(?P<slug>)/$']
I got this error using django 2.2 here are my codes urls.py app_name = 'products' urlpatterns = [ url(r'^$', product_list, name='product-list'), url(r'^(?P<slug>.*)/$',single, name="single_product"), url(r'^category/(?P<slug>.*)/$',category_single,name="category") ] views.py in product model def get_absolute_url(self,): return HttpResponseRedirect(reverse('single_product',args=[self.slug])) tempplate <h3>{{ product }}</h3> <p>{{ product.description }}</p> <p>{{ product.get_price }}</p> <p> <a href ="{% url 'products:single_product' %}" class = "btn btn-primary" role = "button"> View Product </a> -
How to transform only the values of a queryset into a new array of dictionaries in django
I want to pass data from my view to my template in an efficient way. Specifically I need an array with a dict inside of it like so: arraydict = [{key:value}, {key:value} ...] Right now this is what I do: class VisualizationView(ListView): template_name = 'visualize.html' model = UrlTime def get_context_data(self, **kwargs): context = super(VisualizationView, self).get_context_data(**kwargs) #Extracts the months and counts them context['months'] = (UrlTime.objects.annotate(month=ExtractMonth('timestamp')).values('month').annotate(c=Count('id'))) this counts my months. Printing our my {{ month }} in my django template gives me back this queryset: <QuerySet [{'month': 5, 'c': 313}, {'month': 6, 'c': 1961}]> So far so good. My idea is to visualize my data with d3.js for which I need well-strucutred data. So I would like to transform this queryset into something like: data = [{5:313}, {6:1961}]. Basically creating a dict of the values of the queryset and then put it into an array. (Even better would be data = [{May:313}, {June:1961}]) I tried the .values() method which breaks my count method. Also I tried to put it into a list like so: list(UrlTime.objects.annotate(month=ExtractMonth('timestamp')).values('month').annotate(c=Count('id'))) (this works but gives me back a list with dict of keys and arrays like so: [{'month': 5, 'c': 313}, {'month': 6, 'c': 1962}] I also did … -
FOREIGN KEY constraint failed because of models.DO_NOTHING
I have this snippet of code for models.py class Provider(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) provider = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=True) when ever I tried to delete an object I faced an error says : django.db.utils.IntegrityError: FOREIGN KEY constraint failed I faced this issue on django 2.x , since every thing was perfect on 1.11. I made a little search I found may this issue happen by this part on_delete=models.DO_NOTHING, So how could I fix it with kepping every thing as it is ? -
Django TypeError in version 2.2.1 : render() got an unexpected keyword argument 'renderer'
I was actually solving this error by editing the django file "boundfield.py" by removing the renderer value.I also tried using django 2.0.x instead of the newest version as the older version is not having this issue. I know this is not the right way to solve this issue. Can anyone tell me what's the problem and is there any way that could help me solve this error if I am using django 2.2.1 ? -
Distinguish which field has changed in signal.instance , Django/signals
Lets say I have a model called BookModel with 4 fields : (title, author, price, publish_year). And I have a handler in signals: @receiver([post_save, post_delete], sender=BookModel) def signal_handler(sender, instance, **kwargs): ….. Question is how to distinguish a situation when specific model field has changed during save(). For example if price has changed I want to do stuff. Better explain in pseudo code... @receiver([post_save, post_delete], sender=BookModel) def signal_handler(sender, instance, **kwargs): # pseudo code bellow if field “price” has changed: do stuff else: do nothing According the docs if I use “update_fields” in save() - it is possible, but what if I dont use it??? Also is it possible to distinguish a situation when I received signal from post_save or from post_delete still using 1 handler? @receiver([post_save, post_delete], sender=BookModel) def signal_handler(sender, instance, **kwargs): # pseudo code bellow if signal is post_save: if field “price” has changed: do stuff else: do nothing else: do other stuff Thanks -
Re-indexing in elasticsearch
In my project, the index command is taking around 5 hours to complete the indexing of entire records in the database. If I want to re-index the data it would take the same amount of time and with the increasing storage, indexing would consume so many hours which is not feasible. Is there any better way to re-index only the updated or deleted data in lesser time? I know we can use elasticsearch-reindex for this but I'm not totally aware of it's usage. Can someone suggest any better alternative ways and provide a sample code if possible? Thanks a lot in advance!! -
ListCreateAPIView post method has stopped working
For some reason my very simple view is blowing up when I attempt to make post() request to it. Here is some of there error message I get: IntegrityError at /api/v1/spi/locations/ null value in column "site_id" violates not-null constraint DETAIL: Failing row contains (29, 2019-06-19, location_a, 2019-06-19, null). Here is my view: class LocationList(generics.ListCreateAPIView): # using get_queryset().order_by('id') prevents UnorderedObjectListWarning queryset = Location.objects.get_queryset().order_by('id') serializer_class = LocationSerializer permission_classes = (SPIPermission,) Nothing to it. Here is the my LocationSerializer class: class LocationSerializer(serializers.ModelSerializer): site = SiteSerializer(many=False, read_only=True) class Meta: model = Location fields = '__all__' I added the line ... site = SiteSerializer(many=False, read_only=True) ... so my client would get the full site data instead of just an id. Is that causing my problem? Here are the Site and Location models: class Site(models.Model): create_date = models.DateField(auto_now_add=True) name = models.TextField(max_length=150, null=False, unique=True, verbose_name="Site name") update_date = models.DateField(auto_now=True) def __str__(self): return self.name class Location(models.Model): create_date = models.DateField(auto_now_add=True) name = models.TextField(max_length=150, null=False, unique=False) site = models.ForeignKey(Site, null=False, on_delete=models.PROTECT) update_date = models.DateField(auto_now=True) @property def site_name(self): try: return self.site.name except Exception as ex: logging.getLogger("capman").error(ex) return 'Unknown' def __str__(self): return self.name -
How To Remove Row in django-extra-views?
In ModelFormSetView how to delete row here is my code how can I manage delete row in Django-extra-views I am trying with normal if formset.deleted_forms: for obj in formset.deleted_forms: obj.delete() Html {{ formset.management_form }} {% for object in formset %} {% for hidden in formset.hidden_fields %} {{ hidden }} {% endfor %} <tr class="formset" class="even pointer">{{ object.id }} <td class=" ">{{ object.as_p }}</td> <td class=""></td> </tr> {% endfor %} View this is general view how can I manage DELETE filled in this class MeasurementPropsUpdateViews(ModelFormSetView): model = MeasurementProps form_class= MeasurementPropsForm template_name = "master/measurementprops_form.html" def get_queryset(self): pk = self.kwargs.get('pk') current_user = self.request.user return self.model.objects.filter(ProductName=pk, user=current_user) def get_success_url(self): return reverse("tailoringproducts") def formset_valid(self, formset): for docs_form in formset: docs_form.save(commit=False) if formset.deleted_forms: for obj in formset.deleted_forms: obj.delete() docs_form.instance.ProductName_id = self.kwargs.get('pk') docs_form.instance.user = self.request.user docs_form.save() messages.success(self.request, "Measurement Properties Updated successfully") return HttpResponseRedirect(self.get_success_url()) def formset_invalid(self, formset): messages.error(self.request, "Form getting invalid") return self.render_to_response(self.get_context_data(formset=formset)) -
How to run a Python code using CLI(Command-Line-Interface) in Chrome?(OS Handling)
How can I use CLI on google chrome to minimize CPU usage and run a python code using Django?I even want to generate a Log file to track the run flow. In short I want to add OS handling to my Python code(using Django).(My code is regarding fetching 2.5 million data from database and write them to an excel sheet which has three sub sheets.) Please help me regarding this. -
Can I use MariaDB ColumnStore with Django (Django-ORM)?
I have a Django project which uses MariaDB (engine - django.db.backends.mysql). I would like to user MariaDB ColumnStore instead - is it possible? Will I need a different ORM engine? Also, I develop on Windows 10 Pro PC and plan to set up ColumnStore using docker containers provided by MariaDB. This should not be an issue, right? Thank you -
How to apply one specific change to database after 'makemigrations' command?
I added a field to one of my models, but in the 'models' folder I have two other python files which have only View models from which I query views in my database. When I run the makemigrations command, the new migrations file that is created includes also adding these view models to my database as tables (which I don't want to). How can I ignore these changes, and only commit the one addition of a field to an actual table on the database. I think I maybe have to delete the migrations.CreateModel... in the new migrations file and only keep the migrations.addField... , then run the 'migrate' command. I didn't proceed with this because I'm not sure and maybe it will mess up my database in some way. Thanks in advance to anyone who can help. -
A way to access loop index from Django formset loop?
In Django framework templates you can loop through a formset like so: {% for form in formset %} {{ form }} {% endfor %} Is there a way to access the index of the loop? Perhaps something like this: {% for form in formset %} {{ form }} {{ form.index }} {% endfor %} Which should render 0, 1, 2,... prior to each form. -
How does gunicorn deploy django better?
I am using nginx with gunicorn and django. I would like to know Question: What are the benefits using gunicorn compared to just using django's runserver alone -
Pass parameters defined “in the buttons”(template) to CRUD-view
I have a table, where I add in the last column of every row the buttons “delete” and “edit”. I do this with the url + parameters in the href in the template (see below). I wrote a function for every href + parameter and the scripts work. <form method="post"> {% csrf_token %} <input type="hidden" name="projekt_id" value="{{objekt.id}}" /> <a class="btn btn-outline-secondary btn-sm" href="{% url 'check:remove_project' objekt.id %}" role="button">delete</a> <a class="btn btn-outline-secondary btn-sm" href="{% url 'check:edit_project' objekt.id %}" role="button">edit</a> </form> Since i need such tables very often I want to handle the entire functionality (view the data/edit/delete/create) in one single view (I already have this in one template). My idea/wish is to pass the name= and value= from inside the buttons to the view. There I can distinguish for the appropriate functions - by if-statements- between edit/delete/view/create… How can the parameters be passed from the BUTTONS in template to the view? Where is the documentation? I wonder if there is a more elegant way to solve this? (maybe a combination of class based views?) -
Need to protect my directory on ubuntu server so the ubuntu users with access to server cannot see my source code
Hi i am new to ubuntu and security stuff. i have deployed my django project using apache2 and mod-wsgi and angular6 project on aws ec2 instance (ubuntu server). Now i have to deploy the same project in other organisations private inhouse server. So all my source code will live in their server so i need to make sure that they cannot read, copy or access my django source code which will be on their server. Please help me out. Have tried searching on google but i am unable to find anything to help me out achieve this. -
Form Problems - Setting Initial Value
I am trying to set the initial value of a field on a form. The field is not part of the model, but when I try and set it to a value the field is blank. From my research it could be because the form is "bound" which makes some sense to me, but in this case the field is not part of the model. My form: #Form for editing profile class CatForm(forms.ModelForm): pictureid = forms.CharField() class Meta: model = Cat fields = ['name'] def __init__(self, *args, **kwargs): picid = kwargs.pop("pictureid") print(picid) super(CatForm, self).__init__(*args, **kwargs) self.fields['pictureid'] = forms.CharField(initial=picid, required=False) The model: class Cat(models.Model): name = models.CharField(max_length=34,null=False) I was expecting it to set the field to the value of the initial attribute, but it doesn't. I have tried testing it by directly adding a string, but doesn't set. -
I want to create a website where users will be posting to the site, How would I make each post appear in a separate card?
Am creating a website where user will be posting information in the site, but when I post in the site, all post appear in a single card while I want each post to appear in a separate card, How would I do this?? would I have to use Javascript in the front end or python in the back end to accomplish this, and how? Am using python 3.6.8, and django 2.1.8, I have written a code but all post appear in single materialize card views def homepage(request): return render(request=request, template_name="main/home.html", context={"documents":Documents.objects.all} -
How to fix: Domain name not working in digital ocean's droplet. Using Nginx, docker-compose, django
I'm trying to set up a domain name to my digital ocean’s droplet. While the IP address works perfectly, the domain name doesn’t seem to do anything and get “This site can’t be reached”. Checking https://whois.net/ it shows the DNS nameservers are pointing to right direction which are digital ocean’s name servers [NS1.DIGITALOCEAN.COM, NS2.DIGITALOCEAN.COM, NS3.DIGITALOCEAN.COM], and using www.whatsmydns.net it shows the domain name has propagated. Digital Ocean’s DNS records are the following: A--domain.tk--directs to X.X.X.X CNAME--www.domain.tk is an alias of domain.tk NS--domain.tk--directs to ns1.digtalocean.com NS--domain.tk--directs to ns2.digtalocean.com NS--domain.tk--directs to ns3.digtalocean.com I’m using a .tk domain using freenom and have configured the same domain nameservers over there. My NGINX configuration is the following: upstream jaciv_server { server djangoapp:8000; } server { listen 80; server_name domain.tk www.domain.tk; location / { proxy_pass http://jaciv_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /opt/services/djangoapp/static/; } location /media/ { alias /opt/services/djangoapp/media/; } } My docker-compose.yml is the following version: '3' services: djangoapp: build: . volumes: - .:/opt/services/djangoapp/src - static_volume:/opt/services/djangoapp/static - media_volume:/opt/services/djangoapp/media domainname: jaciv.tk networks: - nginx_network - database1_network depends_on: - database1 nginx: image: nginx:1.13 ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/opt/services/djangoapp/static - media_volume:/opt/services/djangoapp/media depends_on: - djangoapp - redis networks: - … -
URL Template Tag works in one instance, but can't find path with kwargs of '{'pk': ''}' in another
I've assigned a navbar link a URL template tag using named paths, and I'm passing the keyword argument of pk to that URL. When I click on the link directly, it passes the kwarg as it should and I get the DetailView that is intended. However, when i attempt to view other DetailView's in my app, I receive the error of: Reverse for 'my_company_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['console/(?P[0-9]+)/mycompany/$']. .html snippet <a class="dropdown-item" href="{% url 'user_console:my_company_detail' pk=request.user.primary_company_pk %}">My Company</a> urls.py urlpatterns = [ path('login/',auth_views.LoginView.as_view(template_name="user_console/login.html"),name='login'), path('change-password/',auth_views.PasswordChangeView.as_view(template_name="user_console/change-password.html"),name='change_password'), path('home/',views.HomepageView.as_view(),name='home'), path('logged-out/',auth_views.LogoutView.as_view(template_name='user_console/logged_out.html'),name='logged_out'), path('requests/',views.RequestListView.as_view(),name='request_list'), path('request//',views.RequestDetailView.as_view(),name='request_detail'), path('consumers/',views.ConsumerListView.as_view(),name='consumer_list'), path('consumer/create/',views.ConsumerCreateView.as_view(),name='consumer_create'), path('consumer//',views.ConsumerDetailView.as_view(),name='consumer_detail'), path('companies/',views.CompanyListView.as_view(),name='company_list'), path('company//',views.CompanyDetailView.as_view(),name='company_detail'), path('company/create/',views.CompanyCreateView.as_view(),name='company_create'), path('request//edit',views.RequestUpdate.as_view(),name='request_update'), path('request/create/',views.RequestCreateView.as_view(),name='request_create'), path('requests/export-all/',views.RequestExport,name='export_all_requests'), path('requests/import/',views.RequestImport,name='import_requests'),path('mycompany//',views.MyCompanyDetail.as_view(),name='my_company_detail'), ] .html that throws error I click on this href: {{request.pk }} and I receive the error: NoReverseMatch at /console/request/201/. Reverse for 'my_company_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['console/(?P[0-9]+)/mycompany/$'] -
Vs code remote container not stopping on breakpoints
I have a setup with both a devcontainer.json and a launch.json with the new Remote Container plugin in vs-code. But I cant get the breakpoints working. I get the app to launch and can browse it, but the breakpoints are not getting hit, am I missing something in my launch.json? { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "0.0.0.0:8000", ], "env": { "PYTHONUNBUFFERED": 1, "ENV": "local", "DJANGO_SITE_ID": 1, "DJANGO_SETTINGS_MODULE": "project.settings.local1", } } ] } -
How to display all the user_permission of user in django template
Here i am trying to display all the user_permissions of some particular user but i am getting nothing though is_superuser=True for this user.How can i do it ?? views.py def profile_user(request,id): user = get_object_or_404(User,id=id) user_permissions = user.user_permissions.all() #user_permissions = Permission.objects.filter(user=user) return render(request,'user_profile.html',{'user':user,'user_permissions':user_permissions}) template <p>User Roles: <b> {% for permission in user_permissions %} {{permission}} {% endfor %} </b></p> -
Change 5th number from list
I have a one function for my calendar def formatweek(self, theweek, events): week = '' for d, weekday in theweek: #return f'<tr style="color:blue";> {week} </tr>' week += self.formatday(d, events) return f'<tr> {week} </tr>' where theweek is a list of pairs: [(1, 0), (2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6)] [(8, 0), (9, 1), (10, 2), (11, 3), (12, 4), (13, 5), (14, 6)] [(15, 0), (16, 1), (17, 2), (18, 3), (19, 4), (20, 5), (21, 6)] [(22, 0), (23, 1), (24, 2), (25, 3), (26, 4), (27, 5), (28, 6)] [(29, 0), (30, 1), (31, 2), (0, 3), (0, 4), (0, 5), (0, 6)] Where the first number(for example(1)) in pairs is day in month (1.januar) and the second is a number for week name (0-Monday, 1-Thuesday etc...) d and weekday become an int in loop. d = days of month (1,2,3,4....)and Weekday = number for days (Mon - 0, Tue - 1 etc...). It returns this return f'<tr> {week} </tr>'for the table. And I would like to make and 5th and 6th number in week (Saturday, Sunday) to return not only above one but also something like this return f'<tr style="color:blue";> {5 (or … -
How to monkeypatch a Python class for an entire Django application?
The main permission checking methods in Django REST Framework, BasePermission's has_permission and has_permission, both return True, effectively making any permission checking allow by default. Since this is counter to a security mindset and OWASP recommendations I would like to fix the implementation locally before reporting a bug. I could fix it for my own classes by subclassing BasePermission but I want to ensure that every subclass of BasePermission used anywhere does deny by default. Can I replace the functionality of these two methods for every subclass in my Django system? To be clear, I am not trying to do this for testing purposes.