Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pass an url to template for reusable code
My question is if it's possible to pass a named url from the view to the template for reusing template code, something like this, but it's passed as raw string. class PersonCreateView(CreateView): ... def get_context_data(self, **kwargs): context = super(PersonCreateView, self).get_context_data(**kwargs) context['myurl'] = "{% url 'people:person-index' %}" return context And in the template: <a class="btn btn-default pull-right" href="{{ myurl }}" role="button"> Thanks! -
Django : change allauth singup template
I want to change the template of socialaccount/singup template in a project that i am working on django 1.11.0, here's the template : {% extends "socialaccount/base.html" %} {% load i18n %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans with provider_name=account.get_provider.name site_name=site.name %}You are about to use your {{provider_name}} account to login to {{site_name}}. As a final step, please complete the following form:{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'socialaccount_signup' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> {% endblock %} How can I replace it with my own template in my project ? -
Django: Exclude Extra Users
Here's my Query, users = User.objects.all() # contains all users extra_users = Models.objects.filter(user=request.user) # contains few users related to request.user Hoe can I exclude extra_users from users? -
DJango Querysets Filter
clients = Client.objects.filter(user_id=request.user) quotes = Quote.objects.filter(customer_act_id=clients) I have the above code and I am trying to display the users clients and quotes to the user. The clients display fine but the quotes only show the quotes for the FIRST client and not all of them. Any help is appreciated. Relationships: User has_many clients(user_id FK) has_many quotes(client_id FK) -
Anaconda virtual environment django in windows
I created a virtual environment using anaconda in windows, and there are a lot of stuff installed within the virtual environment, when I tried to add my project to the github, it listed all the files within the directory to be committed and showed the follow warnings: LF will be replaced by CRLF. how can I properly set up a virtual envs by using Anaconda3 to start my django project, many thanks. -
Django insert script
I would like to have one time insert script in django to the database configured in the settings. This script could be rerun and would only insert once i was going to have something like my_list =[{key:value},{key:value}] with transaction.atomic(): for item in my_list: my_model = a_model(my_key=item['key']) my_model.save() But I don't know how to get it running -
using __import__ on a module in a different directory python. django
I am attempting to import a model from another app in django. The following attempts fail fails: from venueadmin.models import VenuePermissions fails how: Python is not able to located VenuePermissions, i guess circular reference? from django.apps import apps suitscity = apps.get_model('suitsandtablesadmin', 'City') fails how: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. so then I tried importing using __import__ suitscity = __import__('suitsandtablesadmin.models') suitscity = getattr(suitscity, 'City') and suitscity = __import__('suitsandtablesadmin/models') suitscity = getattr(suitscity, 'City') all of which did not work because City is in a different directory suitsandtablesadmin how can I make any one of these work -
Displaying models' instances in Django admin index page
I'm trying to modify admin page in Django. I want my admin index page to display the names of my models as well as those models' instances just like in the change list page. How can I do that without modifying Django core files? -
The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example
I have a Python/Django app which sometimes has more than 100 users logged in. One day, I found this in Django error log: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. Although the message is written in quite understandable English, I have no idea what actually happened why it happened whether I need to worry about it if yes, how can I prevent this from happening again I found a question with almost same title but the difference is that I do not have anything about caching in my settings. If you need any pieces of code, just please let me know in the comments. Thanks for your time! -
Django - remove duplicates records from DB
I want to set 'unique_together' on my DB (postgres). The problem is that I may already have duplicates on DB, so migration would probably not work. So as I see it - before the deployment I need to run some script to remove all duplications (leave only one of each). I prefer doing it with Django Custom Command. The table 'mapping' looks something like - Id, user_id, user_role, project_id, user_type. I want to set 'unique_together' for all of them. And the script I use to retrieve duplicated rows is- duplicates = (Mapping.objects.values('project_id', 'user_id', 'user_type', 'user_role').annotate( count=Count('id')).values('project_id', 'user_id', 'user_type', 'user_role').order_by(). filter(count__gt=1)) It returns list of objects that contains the duplicated attributes. for example: QuerySet [{'user_id': '2222', 'user_type': '1', 'user_role': '1', 'project_id': UUID('c02bda0e-5488-4519-8f34-96b7f3d36fd6')}, {'user_id': '44444', 'user_type': '1', 'user_role': '1', 'project_id': UUID('8c088f57-ad0c-411b-bc2f-398972872324')}]> Is there a way to retrieve the Ids directly? Is there a better way? -
django - allauth and rest-auth facebook login token does not work with JWT authentication
I've followed the both packages documentations and using example from rest-auth doc. I've followed all the steps and I can successfully use this API to register/login user with facebook. API returns me token and user object but this token is not working with JWT authentication. But if I set this user's username in the db and then post the facebook login request again then returned token works fine. What does this social authentication process has to do with username? Is there something I need to do to properly configure it? I am using custom user model and have both username and email for authenticating users. Please let me know if any further info is needed for figuring out the problem. -
NoReverseMatch with get_absolute_url
So I've been stuck on this for a couple days now. I have a list of links made up of queryset objects. Clicking on each link should take me to that object's detail view. But I'm getting the following error: NoReverseMatch at /idea_tracker/shoppinglist/ Reverse for 'views.recipient_detail' not found. 'views.recipient_detail' is not a valid view function or pattern name. This is my first question on here and I apologize if there's not enough/too much/incorrect information. Just let me know. I'd really appreciate any help finding the error. My model: class Recipient(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthday = models.CharField(max_length=10, blank=True) notes = models.TextField(max_length=255, blank=True) def __str__(self): return "{} {}".format(self.first_name, self.last_name) def get_absolute_url(self): return reverse( 'views.recipient_detail', args=(), kwargs={'recipient_id': str(self.id)} ) class Gift(models.Model): name = models.CharField(max_length=30, blank=True) model_number = models.CharField(max_length=30, blank=True) price = models.DecimalField(default=0.00, decimal_places=2, max_digits=6) recipients = models.ManyToManyField(Recipient, blank=True) purchased = models.BooleanField(default=False) def __str__(self): return "{}".format(self.name) My views: def shopping_list(request): recipients = models.Recipient.objects.prefetch_related('gift_set').\ all().order_by('last_name') gift_list = models.Gift.objects.all() total = [] for y in gift_list: total.append(y.price) total_price = sum(total) return render(request, 'idea_tracker/shoppinglist.html', { 'recipients': recipients, 'total_price': total_price }) def recipient_detail(request, pk): recipient = get_object_or_404(models.Recipient, pk=pk) gift = recipient.gift_set return render(request, 'idea_tracker/recipient_detail.html', { 'recipient': recipient }) My url: urlpatterns = [ url(r'^shoppinglist/', views.shopping_list, … -
django model save to several tables
The save method saves instance into two different tables, AgencyBeforeReg and Agency, i have a problem saving Services field which is manyToMany field, how can it be done? def save(self, force_insert=False, force_update=False, using=None): if self.id and self.active: self.sign = 'f' if not self.active: self.sign = 'c' self.deactivate_date = datetime.datetime.now() super(AgencyBeforeReg, self).save(force_insert, force_update, using) agency = Agency.objects.create( id=self.id, unpf=self.unpf, unp=self.unp, egr=self.egr, title=self.title, reg_date=self.reg_date, reg_organ=self.reg_organ, post_index=self.post_index, place=self.place, office=self.office, # services=self.services, ins_date=self.ins_date, edit_date=self.edit_date ) agency.services.add() -
django StreamingHttpResponse response to download in angular4 as file
We have a site prepared in django and the front end is angular 4 when django return the response we have to get the response and download it as a file. -
Migrating social_auth to django_social using Django 1.11 and Python 3.6
I'm having problem while trying to migrate social_auth module to django_social using Django 1.11 and Python 3.6. I have some models in my models.py file that uses from social_auth.signals import pre_update, socialauth_registered from social_auth.backends.facebook import FacebookBackend from social_auth.backends.twitter import TwitterBackend but I can't find the equivalent to social_auth.signals into django_social Are they deprecated? Is there a newer version to use them? -
Django Models to Template
This might be a simple questions, but please keep in mind this is my first Django project. I have the following models: User Client Quote The user has many Client which has many Quotes How can I render the latest three quotes to the view? Regardless of the client. How can I render back all of the quotes for a particular client? How can I ensure that other Users clients/quotes are not seen unless it is their client/quote. Thanks in advance, CH -
Form to edit specific instance of model
I know this question has been asked before but I have read through the answers and none of them sufficed. I am trying to make a job board site, where an employer can sign up and post jobs. So there is an Employer object and each employer can post as many Jobs as they want. I am not sure how to create a form where a particular model instance can be edited. The model Job: poster = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=50) establishment_name = models.CharField(max_length = 50) details = models.TextField(max_length = 2000) salary = models.CharField(max_length = 20) address = models.CharField(max_length = 50) city = models.CharField(max_length = 50) state_choices = ( #long list omitted on purpose ) state = models.CharField(choices=state_choices, max_length = 20) zip_code = models.CharField(max_length = 10) def __str__(self): return self.job_title + " - " + self.establishment_name \ + ", " + self.poster.user.first_name + " " +self.poster.user.last_name I have a form to post jobs: class JobPostForm(ModelForm): class Meta: model = Job fields= ('job_title', 'establishment_name', 'details', 'address', 'city', 'state', 'zip_code', ) a view to post jobs: if request.method == 'POST': form = JobPostForm(request.POST) if form.is_valid(): job_object = form.save(commit=False) job_object.poster = request.user.employer job_object.save() return redirect('employer_home') else: form = JobPostForm() and a template … -
Attempting to create view for a list of all books on loan to the current user
I am attempting to create a view that lists all the books on loan to a specific user in my library app. However I keep getting the following error : When the user clicks on the books borrowed link the user should be redirected to the list view which contains the books the user borrowed with the name of the book rendered as a link that allows the user to access the detail view of the book. Here is the code : models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from datetime import date class Genre(models.Model): genre_name = models.CharField(max_length = 200, help_text = "Enter a book genre") def __str__(self): return self.genre_name class Mind_Book(models.Model): Title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null = True) Summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book") isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href = "https://www.isbn-international.org/content/what-isbn">ISBN Number</a>') genre_relation = models.ManyToManyField(Genre, help_text = "Selct a genre for this book") language_relation = models.ForeignKey('Language', on_delete=models.SET_NULL, null = True) def __str__(self): return self.Title # returns the url to access a particular book instance def get_absolute_url(self): return reverse('book-detail', args= [str(self.id)]) def genre_representation(self): return ', '.join([genre_relation.genre_name for genre_relation in self.genre_relation.all()[:3]]) genre_representation.short_description = 'Genre' import … -
Django admin user permissions
On my Django admin page, I am trying to get the user permissions fieldsets. But the page doesn't load after I put user_permissions. All the other fields work except this. I am trying to manage permissions through admin page and give a user a specific permissions by moving some individual permissions. class UserAdmin(BaseUserAdmin, HijackUserAdminMixin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'first_name', 'last_name', 'hijack_field') list_filter = ('first_name', 'last_name') # change form fields fieldsets = ( ('User', {'fields': ('username', 'email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name',)}), ('Permissions', {'fields': ('is_staff', 'is_superuser', 'groups')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ('User Permissions', {'fields': ('user_permissions',)}), ) All the fields work except user_permissions. I have checked the class UserAdmin from which it extends has this. @admin.register(User) class UserAdmin(admin.ModelAdmin): add_form_template = 'admin/auth/user/add_form.html' change_user_password_template = None fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), I am able to view all the fields except user_permissions.Is … -
Django - getting user permissions in a view only shows model views, not custom permissions
Im trying to get a list of user permissions in a script that pulls info from Django (not using a request). I have managed to do this, however when I look at a list of permissions, the custom permissions ive added via a models meta are not in this list. my script: from django.contrib.auth.models import User from django.contrib.auth.models import Permission result = '' i = Inbox(settings.ON_CALL_MAILBOX_AUTH,getNow=False) # filter sample (IsRead eq false) and (Subject eq 'who') i.setFilter("(IsRead eq false)") try: i.getMessages() except: admin_email('Email Processing Failed','Failed to get messages, either all the messages are read or credentials are incorrect') result = 'Failed to get messages, either all the messages are read or credentials are incorrect' for mail in i.messages: #get details of mail sender = Message.getSender(mail)['EmailAddress']['Address'] subject = Message.getSubject(mail) subject = subject.strip() result = 'unread mail from {0}'.format(sender) can_email_query = False user = User.objects.filter(email=sender) if user: user_permissions = Permission.objects.only('name').filter(group__user=user) if "can email query" in str(user_permissions).lower(): can_email_query = True so im looking for a perm ive set in my model of user profile class UserProfile(models.Model): mpls_m_subscriptions = models.CharField(max_length=50,verbose_name="MPLS Maintenance Subscription",choices=settings.SUBSCRIPTION_TYPE,blank=True,null=True) user = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: permissions = ( ("can_email_query", "Can email query"), ) this perm is assigned to my user group … -
dynamically importing models in django throws models not ready
in my venues app model file I am dynamically adding models I need to do work. from django.apps import apps state = apps.get_model('suitsandtablesadmin', 'State') suitscity = apps.get_model('suitsandtablesadmin','City') suitsneighboorhood = apps.get_model('suitsandtablesadmin', 'Neighborhood') venuetypes = apps.get_model('suitsandtablesadmin', 'VenueTypes') venueseatingtypes = apps.get_model('venueadmin', 'SeatingTypes') costofvenue = apps.get_model('venueadmin', 'VenueCost') venuecusines = apps.get_model('venueadmin', 'Cusines') roomprivacy = apps.get_model('venueadmin', 'Roomprivacy') roomamenities = apps.get_model('suitsandtablesadmin', 'Amenities') I am doing this because a regular import statement will not work. Python says it can find the model, I am guessing because of circular importing. I see from this stackoverflow answer that it may be best to import the entire app into the file but how will that help? And is there a better solution? Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet I also have yet to create any type of migrations is that a cause? Relevant part of the trace back below `File "/home/ri`ckus/Documents/softwareProjects/211hospitality/suitsandtables/backend/suitsandtablesbackend/virtualsuits/suitsandtables/venues/models.py", line 7, in <module> state = apps.get_model('suitsandtablesadmin', 'State') File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/suitsandtablesbackend/virtualsuits/local/lib/python2.7/site-packages/django/apps/registry.py", line 193, in get_model self.check_models_ready() File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/suitsandtablesbackend/virtualsuits/local/lib/python2.7/site-packages/django/apps/registry.py", line 132, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Django OneToOneField on foreign table
I'm trying to setup a new server with foreign tables (using postgres_fdw) that weren't foreign tables previously, and I have some OneToOneFields pointing to these tables. This doesn't work out of the box - OneToOneFields use foreign keys, and postgres_fdw does not support foreign keys for foreign tables. The foreign tables are in a read-only database on the same server. Is there an easy way to get this working? -
Deploying django application on nginx server rhel - 400 bad request Request Header or cookie too large
I'm currently trying to deploy a Django app on a REHL 7.4 server using Nginx. I've followed these tutorials : https://simpleisbetterthancomplex.com/tutorial/2017/05/23/how-to-deploy-a-django-application-on-rhel.html https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 The virtualenv and the nginx server seems to be allright. However I'm struggling with two errors: Either I got a 500 error because of worker_connections parameter value (below are logs): 13494#0: *1021 1024 worker_connections are not enough while connecting to upstream, client: 192.168.1.33, server: 192.168.1.33, request: "GET /Syc/login HTTP/1.0", upstream: "http://192.168.1.33:80/Syc/login", host: "192.168.1.33" Either I increase worker_connections value to > 4096 and I get a 400 error like in this thread 400 Bad Request - request header or cookie too large Below are my nginx.conf and app.conf, please let me know if there are configuration mistakes and thanks in advance for any help. nginx.conf: include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } # set open fd limit to 30000 worker_rlimit_nofile 30000; http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; } server { listen 80 default_server; listen … -
Passing parameters from ModalFormView to a form
I'm trying to send a list of names as choices for a modified choice field, so I can search for the choices by typing some text within the form's field, here's my view: class OfferFormModal(ModalFormView): def __init__(self, *args, **kwargs): super(OfferFormModal, self).__init__(*args, **kwargs) self.title = "ServiceOffer" services = Service.objects.filter(provider=Provider.objects.get(id=9)) choices = list() for service in services: choices.append(service.name_service) self.form_class = OfferServiceForm(data_list=choices) def form_valid(self, form, **kwargs): data = form.cleaned_data ... self.response = ModalResponse('Done', 'success') return super(OfferFormModal, self).form_valid(form) My Form looks like this: class OfferServiceForm(forms.Form): service = forms.CharField(required = True,label="") description = forms.CharField( required=True, label="", widget=forms.Textarea ) def __init__(self, *args, **kwargs): _service_list = kwargs.pop('data_list', None) super(OfferServiceForm, self).__init__(*args, **kwargs) self.fields['service'].widget = ListTextWidget( data_list=_service_list, name='service-list', attrs={'placeholder':'Service:'}) I did something similar before in a normal view without issue, but now whenever I try to load this within the ModelFormView I'm met with this error: return form_class(**self.get_form_kwargs()) TypeError: 'OfferServiceForm' object is not callable Why is it not callable as super? Am I missing something? -
django connection error using DjANGO Q package
I create I python function where I use it in my views.py to calculate some numbers but that calculate algorithm take a long time to finish it and I want to avoid long time processing reload page using DJANGO Q package and specific async. but I take this error : ConnectionError at /url/url1/ Error 10061 connecting to localhost:6379. ��� ���� ������ � ���������� ��������,. here my code : views.py import logging from django_q.humanhash import humanize from django_q.models import OrmQ from django_q.tasks import async, Task from simple_search import search_filter import os logger = logging.getLogger(__name__) @login_required(login_url="login/") def app_details(request,slug): if request.method == "POST": test = request.POST.get('car') in1 =test in2=in1*10000 task_id = async('mysite.tasks.myalg', input1=in1, input2=in2) return render(request, 'details.html') tasks.py def myalg(input1,input2): ................... ................... any idea why ?