Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add django-sitegate to a template or existing page?
I have been following the wagtail tutorial here, and have a basic site setup with a few other packages installed and configured. However, while attempting to add in django-sitegate to have user registration and login functionality, I have had nothing but trouble. I am following the sitegate quick example here, which is identical to the instructions in the quick start guide in the documentation. So, I added the following to the top of my models.py from django.shortcuts import render from sitegate.decorators import sitegate_view And I included the following within my 'BlogPage' model in models.py: @sitegate_view # This also prevents logged in users from accessing our sign in/sign up page. def entrance(request): return render(request, 'entrance.html', {'title': 'Sign in & Sign up'}) I then appended the following to my blog_page.html template: {% extends "blog_page.html" %} {% load sitegate %} {% block page_contents %} <div class="my_signin_block"> {% sitegate_signin_form %} </div> <div class="my_signup_block"> {% sitegate_signup_form %} </div> {% endblock %} Which gives the error TemplateSyntaxError at /blog/ <ExtendsNode: extends "blog_page.html"> must be the first tag in the template. However when putting the template code in it's own file, site_gate.html, I get a 404 error when trying to access it via blog/site_gate.html I did a … -
Can I use Django models to preform complex queries on a database?
I want to use django for a database driven app and I want to know if django models permit me to use complex query to fetch data. I have for example this table inside a database: Click to show image I want to extract data resulting from this query. SELECT name FROM movies WHERE year between 1995 AND 2001 AND rank between 6 and 9; How can I do it with Django? -
Custom django widget
I'm playing with django forms and I need to create a custom wiget and process choices args inside this widget. But create_option method doesn't run. What I have now: from django.forms import Select class MySelectWidget(Select): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def create_option(self, *args, **kwargs): print(kwargs) option = super().create_option(*args, **kwargs) print(option) return option class MyChoiceForm(forms.Form): test_field = forms.ChoiceField( widget=MySelectWidget(choices=((1,1), (2,3)))) I know there are render methods which can help also, but I need create_option. -
Django Database Queryset No Field Information
When I run a queryset through my views and pass it to the template all I get is the following: <QuerySet [<ChangeLog: ChangeLog object (1)>, <ChangeLog: ChangeLog object (2)>, <ChangeLog: ChangeLog object (3)>, <ChangeLog: ChangeLog object (4)>, <ChangeLog: ChangeLog object (5)>, <ChangeLog: ChangeLog object (6)>, <ChangeLog: ChangeLog object (7)>, <ChangeLog: ChangeLog object (8)>, <ChangeLog: ChangeLog object (9)>, <ChangeLog: ChangeLog object (10)>, <ChangeLog: ChangeLog object (11)>] How do I show the fields dictionary through my query? views method: def changeres(request): if request.user.is_authenticated: name = request.session.get('name') data = ChangeLog.objects.all() return render(request, 'changeres.html', {'data': data}) -
Django - exclusive lock on table with multiple synced databases
I'm running a Django app with two Postgres databases (running in docker containers locally), a write-only database and a read replica. I've set up the replica database to stream any updates to the master. my DBRouter looks like: def db_for_read(self, model, **hints): return 'read_replica' def db_for_write(self, model, **hints): """ Writes always go to primary. """ return 'primary' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed on either. """ return True def allow_migrate(self, db, app_label, model_name=None, **hints): """ Migration to be done on both. """ return True my issue is that I have an API view that puts an "EXCLUSIVE LOCK" on one of the database tables for concurrency reasons. the view reads some current values from the table and then creates a new row / model instance based on some logic. however, with this read replica setup I am not able to call that endpoint, as it seems to deadlock - the view never returns a response. i am using django rest framework's viewset and wrapping the view in an atomic transaction. the view looks something like class MyViewSet(viewsets.ModelViewSet): @transaction.atomic @decorator that executes exclusive lock on my_table def my_view(self, serializer): # some logic related to my_table serializer.save(...) … -
How to connect an MS Access table to become the backend for a django form?
I want to use a MS Access Table as the backend for a django form. I found that there is a django.pyodbc, but having trouble connecting it through there. I also understand this is not the best option, but this is what I have to work with right now plus this is only going to be for internal use. Has anyone successfully connected them can show an example? DATABASES = { 'default': { 'ENGINE': '', 'HOST': '', 'NAME': '', 'OPTIONS':{ 'host_is_server':True }, } } -
Django: Showing images uploaded via admin
I´m loading images to a model in the admin panel (not in form). I know it only stores a link. When I try to show the image I does not shows. I try the following: {% for x in dataset %} <img src="{{ x.foto_disco.url }}" alt="Caca" style="width: 100%;"> <p>{{ x.foto_disco.url }}</p> {% endfor %} I try to get the image and then show also the link to see where it´s pointing. The file upload works fine. It points to the correct myapp/media folder.But still cant see the image in the template. In the model I have: foto_disco = models.ImageField(upload_to='', blank=True, null=True) In settings I have: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") I urls.py I have: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I can´t figure out which is the problem. Any clues? Thanks! -
icontains and getlist django python
We are trying to return a list of titles for the Django API, in which the title can have a few keywords. So for instance, if we use the __icontains method to search for "money" and "world" (API.com/?keyworld=money&keyword=world) this will return all records that contain money, world or both. The related SQL statement is: select * from news where news_source = 1 or news_source = 2 and news_title like '%money%' or news_title like '%world%' We are trying to use this code to allow the user to have multiple keywords for the icontain as well as multiple sources, so the end goal is: URL.com/?keyworld=money&keyword=world&source=1&source=2 Our code: def get_queryset(self): queryset = News.objects.all() title = self.request.query_params.getlist('title') source = self.request.query_params.getlist('source') if title: queryset = queryset.filter(news_title__icontains=title, news_source__in=source) return queryset The issue is that this is only returning the second keyword if a second keyword is used, and not other keywords prior to what is typed in &keyword=. -
`lookup_field` doesn't work on `ListAPIView`
I am creating a reddit clone. models.py class Subreddit(models.Model): owner = models.ForeignKey(Profile, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='subreddits') class Post(models.Model): owner = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) title = models.CharField(max_length=300) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) urls.py urlpatterns = [ # API Views # SUBREDDIT VIEWS path('r/', ListSubreddits.as_view(), name='reddits'), path('r/<int:r_id>/', DetailSubreddit.as_view(), name='reddits-detail'), path('r/<int:r_id>/posts/', ListPostsOfReddit.as_view(), name='reddit-posts'), ] ListPostsOfReddit class ListPostsOfReddit(ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer lookup_field = 'subreddit__id' lookup_url_kwarg = 'r_id' I am having a problem with the url named 'reddit-posts'. This url tries to get all a particular subreddit whose id is specified in the url as r_id. The problem here is I am getting all the posts and not the posts specific to that subreddit. So if I have 2 posts in subreddit of id=1 and 3 posts of subreddit of id=2, if i goto r/1/posts/, in theory, I should get only 2 posts but practically I am getting all the 5 posts. I have specified the lookup_field and lookup_url_kwarg but that doesn't seem to work. Need help! Thanks! -
Django annotate with casted variable
i want to achieve something complex with a django queryset. My model looks like this: class Mymodel(models.Model): #Model Variables year = models.IntegerField() month = models.IntegerField() date = models.DateField(_("Date"), default=datetime.date.today) score = models.CharField(max_length=50) Unfortunately, 'score' can't change from CharField() to FloatField(), it should be kept as a String. What i need is to sum all scores by year and month. I tried something like this to group all scores with no great success. values = Mymodel.objects.all().values('year', 'month').annotate(Sum('score')).order_by('year', 'month') I tried to cast 'score' before use annotate by doing this. values = Mymodel.objects.all().annotate(scoreFloat=Cast('score', FloatField())).values('year', 'month').annotate(Sum('scoreFloat')).order_by('year', 'month') Once again with no success, since i am getting a KeyError for scoreFloat parameter. Any suggestions? Thanks in advance. -
Can't use 3rd party components with Vue JS as CDN
I'm learning Vue JS to try to make my django app more interactive, and I'm going for the approach of using Vue JS as components in my templates, not as SPA. it's like of JQuery replacement, because of that I'm using CDN version by a script tag at the end of my body element. the problem I'm facing is when I try to use 3rd party components I find most of them require npm installation, and I'm not pretty sure if I want to do that, I'd prefer to keep things simple, so I'm trying to use 3rd party components with CDNs, like this one https://github.com/bliblidotcom/vue-rangedate-picker but I don't know how to configure my current components to use it ! To give you an idea of what I'm trying to do here, I have a component that handles a search form and displays data into table, and I want to add datepicker inside my search form and bind the dates to be passes as parameters in my API calls. -
Cant install Bitnami Django Stack on CentOS 7
I cant install Bitnami Django Stack on CentOS 7. I keep getting an error that says; " Segmentation fault (core dumped) " I am able to easily install the same downloaded package on ubuntu server but NOT on CentOS 7. kindly help thanks. -
Make a copy of a part of a database with foreignkeys in django
I have a number of objects on a yearly basis and want to copy one of them to a new year, with appropriate foreignkeys. The model Realisations below link to a number of Moments, and when I make a new copy I want to "keep" the connection between the new Moment and the new Realisation. Based on what I have found on the Internet I am working on the following piece of code: realis_lista = Realisering.objects.filter(year=thisyear).all() for obj in realis_lista: new_obj = obj moment = Moment.objects.filter(realisering__pk=obj.pk).all() new_obj.pk = None new_obj.year = nextyear new_obj.save() if moment: for mom in moment: new_mom = mom new_mom.pk = None new_mom.realisation = ??new_obj?? What should the last row be? I need to find where new_obj was saved (its pk), but the only idea I have is to use something like n_obj = Realisering.objects.filter(year=nextyear).filter(period=obj.period).... new_mom.realisation=n_obj But there must be a better way. Maybe there is an altogether better way to make this copy? -
Loading image in for loop with jinja2/django
How do I dynamically display an image using jinja2 and django on a webpage. Currently I am trying to load images in a for loop like: {% for img_path in imgs %} <img src="{% static "{{img_path|safe}}" %}" alt="Herb" id="plant-mascot" style="width: 100px"/> {% endfor %} However, this doesn't work. The image path (imgs) is definitely correct. I have also tried loading the same image without passing it as a variable and it displays it. I think I am missing something with jinja and html, I assume jinja isn't passing the text img_filepath to html but an object or something? How do I make this work do I can display an arbitrary amount of images on a webpage? -
Django Admin - 404 Error when logging in
When going to login to the Django admin on my page, I geta 404 error and a "/admin/login/ url is not defined". I only get this error while in the Production of my project - it works just fine locally. I am using A2 hosting and their support team has not been able to help me solve this problem. Another note, the login screen does not look like the standard admin login screen, see first image. The stack trace as well as the error url are seen in the second image. Let me know if you need to see any code, I am more than happy to share I just dont want to be here all day posing all of my .py files when most of them wont matter anyways. -
the queryset attribute of django REST api generic views
I am trying to understand the django rest framework generic API views, the documentation tells me that while overriding methods of the generic views, I shouldn't be accessing the queryset attribute directly and instead access the get_queryset() function because apparently the queryset attribute is evaluated only once, what does the get_queryset() do differently? Does the queryset attribute ever get updated? -
How to combine two tables' data to JSON in Rest Framwork?
My rest framwork serializers is as below: class ResultSerializer(serializers.ModelSerializer): addline = serializers.JSONField(); city = serializers.JSONField(); unitcode = serializers.JSONField(); maid = serializers.JSONField(); class Meta: model = address fields = ('addline', 'city', 'unitcode', 'maid') I have two models: class address(models.Model): addline = models.TextField(primary_key=True) city = models.TextField(primary_key=True) unitcode = models.TextField(primary_key=True) maid = models.TextField(primary_key=True) class dep(models.Model): maid = models.TextField(primary_key=True) unit = models.TextField(primary_key=True) This is example of filter: queryset = address.objects.filter(addline__icontains=‘110A Ave’) The Data Current I get is: [ { "addline": "14075 110A Ave", "city": "Surrey", "unitcode": "U", "maid": 113091 }, { "addline": "14143 110A Ave", "city": "Surrey", "unitcode": "S", "maid": 113104, ] But what I want is when the unitcode is "U", there will be a more item: unit, like as below: [ { "addline": "14075 110A Ave", "city": "Surrey", "unitcode": "U", "maid": 113091 }, { "addline": "14143 110A Ave", "city": "Surrey", "unitcode": "S", "maid": 113104, "unit": [ "A-101", "A-102", "A-103", "A-104"] } ] -
OneToOneField error
I am working on a user registration form, the form is made up of two Django forms, namely, the CustomUserForm and the CompanyProfileForm (i.e. ModelForm). These forms are connected via a OneToOneField that is situated in the CompanyProfile model, as shown in the code below. class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) companyName = models.CharField(max_length=200, blank=False) companyRegNum = models.CharField(max_length=30, blank=True) Below is my CompanyProfileForm class CompanyProfileForm(ModelForm): # keywordsContainer = forms.CharField(widget=forms.HiddenInput(attrs={ # 'id': 'keywordsContainer_id' # })) class Meta: model = CompanyProfile fields = '__all__' widgets = { 'companyName': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'companyNameId', 'name': 'companyName', 'required': 'required', 'data-rule-required': 'true', 'data-msg-required': 'Please enter company name' }), 'companyRegNum': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'companyRegNumId', 'name': 'companyRegNum', 'required': 'required', 'data-rule-required': 'true', 'data-msg-required': 'Please enter company reg number' }), 'contactNumber': forms.TextInput(attrs={ 'class': 'form-control input_field', 'id':'contactNum', 'name': 'contactNumber', 'required': 'required', 'data-rule-required': 'true', 'data-msg-required': 'Please enter contact number' }), 'address': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'addressId', 'name': 'address', 'required': 'required', 'data-rule-required': 'true', 'data-msg-required': 'Please enter the address' }), 'areaCode': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'areaCodeId', 'name': 'areaCode', 'required': 'required', 'data-rule-required': 'true', 'data-msg-required': 'Please enter the areaCode' }), 'deliveryEmails': forms.TextInput(attrs={ 'class': 'form-control textInput', 'id': 'deliveryEmailId', 'name': 'deliveryEmails', 'required': 'required', 'data-rule-required': 'true', 'data-msg-required': 'Please enter the email address(s)' }), 'provinces': forms.Select(attrs={ 'multiple': … -
How to get the .so file from mod_wsgi 4.6.4 releases
I downloaded the zip from https://github.com/GrahamDumpleton/mod_wsgi/releases/tag/4.6.4 but I seem to not be getting something here. On the README it lists all the .so files that are available from downloading the zip but I don't see these files anywhere. Am I missing something here? I'm just trying to get the pre-compiled module for python 2.7 but I can't seem to find it. -
I want to save two rows into table when user accepts a friend request how to implement in django rest framework and postgres
My Table for Friends Relation: user_id = models. Foreign Key (User,on_delete=models.CASCADE) friend_id = models .Foreign Key (User,on_delete=models.CASCADE) created_on = models .Date Time Field(auto_now_add=True,auto_now=False) I want to store the id's of user and friend twice by alternating them. Example: User 1 sends request to User 2 and he accepts it. 1 --> 2 So now the database should store: user_id friend_id created 1 2 (some date) 2 1 (same date as above) How to implement it using Django-rest-framework so that it can handle the operation in single API endpoint when friend accepts the request. -
Replace dictionary values containing array of integers with array of objects
I am currently working with django and I am able to fetch the JSON of my model.But one of the keys of the JSON contains an array of numbers which I need to replace with array of objects of those numbers.Below is the query to get json of the Contexts model queryset = serializers.serialize("json", Contexts.objects.all()) This is what I get [{"model": "app.contexts", "pk": 1, "fields": {"context_name": "tech-experts", "context_description": "this is for tech experts", "context_priority": "H", "users": [1, 3, 4]}}, {"model": "app.contexts", "pk": 2, "fields": {"context_name": "video-conf-issue", "context_description": "bla bla", "context_priority": "H", "users": [4, 5]}}, {"model": "app.contexts", "pk": 3, "fields": {"context_name": "video-conf-issue", "context_description": "bla bla", "context_priority": "L", "users": [3]}}, {"model": "app.contexts", "pk": 15, "fields": {"context_name": "Network debug", "context_description": "Group for debugging network issues", "context_priority": "L", "users": [2]}}] Now I am interested in just the fields values.So I do this result = [i.get('fields') for i in ast.literal_eval(queryset)] So now I get this [{'context_priority': 'H', 'context_name': 'tech-experts', 'context_description': 'this is for tech experts', 'users': [1, 3, 4]}, {'context_priority': 'H', 'context_name': 'video-conf-issue', 'context_description': 'bla bla', 'users': [4, 5]}, {'context_priority': 'L', 'context_name': 'video-conf-issue', 'context_description': 'bla bla', 'users': [3]}, {'context_priority': 'L', 'context_name': 'Network debug', 'context_description': 'Group for debugging network issues', 'users': [2]}] Now as you can … -
Django with Gunicorn- Directory does not exist
Trying to setup my Django app with gunicorn from the guide at https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 I have anaconda on Ubuntu with gunicorn installed. Pretty much the same script as the guide in /etc/systemd/system/gunicorn.service [Unit] Description="Gunicorn application server handling myproject" After=network.target [Service] User = root Group = www-data WorkingDirectory = /home/Desktop/myproject ExecStart = /home/rohan/anaconda3/bin/gunicorn --access-logfile - --workers 10 --bind unix:/home/rohan/Desktop/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target [Service] Environment = SECRET_KEY=secret The error I am getting after doing is sudo systemctl daemon-reload sudo systemctl start gunicorn sudo systemctl enable gunicorn sudo systemctl status gunicorn gunicorn.service - "Gunicorn application server handling narsil" Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2018-06-25 10:53:36 MDT; 10s ago Main PID: 32365 (code=exited, status=200/CHDIR) Jun 25 10:53:36 rohan-VirtualBox systemd[1]: Started "Gunicorn application server handling myproject". Jun 25 10:53:36 rohan-VirtualBox systemd[32365]: gunicorn.service: Changing to the requested working directory failed: No such file or directory Jun 25 10:53:36 rohan-VirtualBox systemd[32365]: gunicorn.service: Failed at step CHDIR spawning /home/rohan/anaconda3/bin/gunicorn: No such file or directory Jun 25 10:53:36 rohan-VirtualBox systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR Jun 25 10:53:36 rohan-VirtualBox systemd[1]: gunicorn.service: Failed with result 'exit-code'. which seems wierd. I double checked(which is what the other solutions on SO recommend) and I … -
AmCharts reload after request fails
I have a Django template, that renders a AmChart chart. The chart is loaded by dataLoader, from an url inside the django (that returns the JSON with the data). If the link returns an error(ex.server is down), the chart freeze in the "Loading Data" part, and if a new request (ex. by modifing the form) is sent, and gets a correct response, the chart will still be frozen in the "Loading Data" part. Is there a way for the chart to render again with the new data after these error, without refeshing the whole page? Known things: The url gives a correct json to the chart. These happens when the link returns a status='(failed)' template: {% extends "reporting_base.html" %} {% load static %} {% load i18n %} {% block container %} <div class="container-fluid"> <div class="row"> <div id="chartdiv" style="width: 100%; height: 800px; background-color: #FFFFFF;" ></div> </div> <div id="tableContainer" class="container-fluid" style="margin-top: 2%;" data-ng-app="videoconferenceRoomsUsage" ng-controller="videoconferenceRoomsUsageController"> {% if campaign %} <div class="row form-inline well"> <h3 id="reportName">{{ campaign }}<h3> {% if campaign.created_by == user %} <a data-url="{% url 'create_campaign' %}?campaign={{campaign.pk}}" id="saveChanges" class="btn btn-success" href="#"> <span class="glyphicon glyphicon-save"></span> {% trans 'Save changes' %} </a> <a data-toggle="modal" data-target="#createCampaignModal" id="editCampaign" class="btn btn-primary" href="#"> <span class="glyphicon glyphicon-edit"></span> {% trans … -
Django: how to alter context dictionary based on request method called
I am passing a generator object results from fx_rates view to template like this: def fx_rates(request): if request.method != 'POST': form = FxForm() results=[] else: form = FxForm(request.POST) if form.is_valid(): scraper = FxScraper() scraper.from_currencies.append(form.cleaned_data['from_currencies']) scraper.dates = form.cleaned_data['dates'].split(" ") scraper.to_currency = form.cleaned_data['to_currency'] results = scraper.results() context = {'form':form, 'results':results} return render(request, 'map_assistant/fx_rates.html',context) In the template for this view I am using the below to display results: <ul> {% for result in results %} <li>{{result}}</li> {% endfor %} </ul> (guess I can change it to {{next(results)}} once the issue described below is solved). The problem is I don't know how to prevent "[]" from displaying when the view is called using GET method (see if clause above). I cannot delete results=[] line because I will get an error when the view is called using GET. Guess I would need to somehow remove results from context dictionary when the method is GET? -
Using F() with annotations including another query expression in Django
This is my (simplified) use case: from django.db import models class MyType(models.Model): whatever = models.CharField() class A(models.Model): type = models.ForeignKey(MyType) class B(models.Model): my_type = models.ForeignKey(MyType) position = models.IntegerField(default=0) I want elements from A sorted by position field of B. So, I'd need to join A and B tables on MyType first. Tried this: A.objects.all().annotate(position=B.objects.get(my_type=models.F('type')).position).order_by('position') Got the error: FieldError: Cannot resolve keyword 'type' into field. Choices are: my_type, my_type_id, position So, Django understands that F('type') is trying to fetch the value of 'type' field of model B. Which, of course, doesn't exist. I wanted to use 'type' field of model A. Looks like F applies to the inner query, not to the outer one. So, is there any better way to get what I want?