Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert raw MySQL into django raw() or rewrite with Subquery
I been looking at this for hours and couldn't figure out how to just go about it. What I want worked but it came at a price of bad database design. Background: I have information that is to be in database, right? The information is quite unrelated and when grouped based on attributes and requirements, I ended up with four tables that work wonderfully. If i place them all in one table, I was unable to define data type and null correctly. In fact, I had to do varchar with allow null only and heavily depend on the front end. Worse yet, on the front end, i have to convert data from string to numbers and dates a lot. Hence, created four tables that are correct from the database design point of view. But i cant seem to do what I want now: Table1: id, name, other_attributes Table2: id,name, other_attributes Now, customers can use those items: Product: id, kind, item_id,user_id Where kind=0 means table1, kind=1 means refer to Table2 With plain MySQL: I was able to use WHEN CASE: SELECT product.id as id, CASE WHEN kind = 0 then (SELECT name FROM table1 WHERE id=item_id limit 1) END as item_type_name … -
Conditions on django filter backend in django rest framework?
I am using Django filter backend on few fields which is working very good. But i want to filter fields when i get specific condition Like if user_type is basic get filter query otherwise get all objects from model. Mine code for filters is here: http_method_names = ['get'] serializer_class = SearchSerializer pagination_class = LargeResultsSetPagination filter_backends = (DjangoFilterBackend,) filter_fields = ('property_zipcode', 'property_state', 'property_county',) The thing i need is: def get_queryset(self): if self.request.query_params.get('basic',None): filter_backends = (DjangoFilterBackend,) filter_fields = ('property_zipcode', 'property_state', 'property_county',) return filtered_query # I want to return filter query from here. queryset = property.objects.all(); return queryset I am new to Django rest framework and django filter backend. If anyone tried do to this thing please help me out. -
Django Template: Have pagination that shows 3 page links at a time, along with last page. If only 3 pages then last page is linked twice
{% for n in objects.paginator.page_range %} {% if objects.number == n %} <li class="page-item active"> <span class="page-link">{{ n }}<span class="sr-only">(current)</span></span> </li> {% elif n > objects.number|add:'-3' and n < objects.number|add:'3' %} <li class="page-item"> <a class="page-link" href="?page={{ n }}&status={{ status }}&entries= {{ entries }}&sorting={{ sorting }}#sorting_block_1">{{ n }}</a> </li> {% endif %} {% endfor %} Here is the part which I am having difficulty with: {% if objects. %} <li class="page-item-spacer"> <span>...</span> </li> <li class="page-item"> <span>{{ objects.paginator.num_pages }}</span> </li> Desired Output: Do not show the last page if there are only 3 pages. Also if there are many pages, and the last 3 are reached, do not show the last page link thats after the '...' -
Issue with sqlite_master while running loaddata in Django after renaming tables
I had a model in app_site that I want to move to app_base, keep the table records intact and replace this model by a proxy in app_site that refers to the model in app_base. I created the following migrations (in order of execution): In app_site: 0005_rename_table__delete_model_state: database_operations = [ migrations.AlterModelTable(name='Sample', table='app_base_sample'), ] state_operations = [ migrations.DeleteModel(name='Sample'), ] operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations), ] In app_base: 0003_set_model_state_as_created: state_operations = [ name='Sample', fields=[ ('id', ...), ('field1', ...), ('etc', ...), ] ] operations = [ migrations.SeparateDatabaseAndState( state_operations=state_operations), ] In app_site: 0006_create_proxy: operations = [ migrations.CreateModel( name='Sample', fields=[ ], options={ 'proxy': True, 'indexes': [], }, bases=('app_base.sample',), ), ] These migrations execute the following steps: * In app_site, rename the model table to match the one that will be created by app_base and set the model state as delete, but doesn't actually delete the model to keep the data. * In app_base, set the model state as created, but doesn't actually create to prevent the table from being created. * In app_site, create the proxy model that refers to app_base's Sample model. This works well for everything except loaddata command. When I try to run this command or tests that use fixtures, the following … -
Server error 500 on live Django site
I just created a new app which works perfectly in my test environment. I uploaded to my live site (evverest.com) which is hosted on Digital Ocean, added it to the settings file, changed the base.html file to have the page linked in the nav, ran collectstatic, ran makemigrations and migrate, and lastly then ran service niginx restart and service gunicorn restart. Side note: I'm sure if needed to run the nginx and gunicorn commands but I was told to do that when I do bigger things on the site so that's what I've been doing. Now all that happens when you visit the site is it give a white screen and says "Server Error (500)". I have tried looking for error logs (I can't find any where people have suggested they were) and all over stack overflow and google looking for potential solutions, however nothing has worked. I literally have no idea what to do now... Please help! -
Values not being passed to template django for second model
First i'd like to clarify that i'm not having issues getting my User detail. I'm having issues getting my report_name to populate in my template. I've defined my profile view as the following where I'm having to pass two arguments for user, one for the formattedusername which ties to every other PK/FK in my model and the username to pull in the user detail, then the ntname for reportacess. Is this the correct way to do it? I've also verified that my owner.formattedusername is printing the correct value that exists in ntname and it is. My formattedusername is the primary key with a OneToOneField on formattedusername, which is the QVReportAccess.ntname :: def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername) print(reportdetail) args = {'user':owner, 'applicationaccess':owner.formattedusername} return render(request, 'accounts/profile.html', args) My template is the following, which the user information pulls in correctly. {% extends 'base.html' %} {% block head %} <title> Profile </title> {% endblock %} {% block body %} <div class = "container"> <h2>{{ user.username }}</h2> <ul> <li>Email: {{ user.email }}</li> <li>Employee First Name: {{ user.first_name }}</li> <li>Employee Last Name: {{ user.last_name }}</li> <li>Coid: {{ user.coid }}</li> <li>Facility: {{ user.facility }}</li> <li>Job Description: {{ user.jobdescription }}</li> <li>Position Description: … -
Django session sets the same variable for all user instances
I am passing an (is_followed) parameter from one class based view FollowToggleAPIView to another UserDetailAPIVIew. I do this using Django session (from reading other thread on this platform) in the hope of displaying the follow-status (true or false) of the user_to_toggle on his UserSingleProfileSerializer. Here are my views: class UserDetailAPIVIew(generics.RetrieveAPIView): ''' Displays a list of a user's posts ''' serializer_class = UserSingleProfileSerializer queryset = User.objects.all() def get_object(self): return get_object_or_404(User, username__iexact=self.kwargs.get('username') ) def get_serializer_context(self): ''' passing the extra is_following argument to the UserDetailAPIVIew ''' context = super(UserDetailAPIVIew, self).get_serializer_context() is_followed = self.request.session.get('followed') context.update({'followed': is_followed}) return context class FollowToggleAPIView(APIView): ''' Uses the custom model manager for user toggle follow ''' def get(self, request, username, format=None): user_to_toggle = get_object_or_404(User, username__iexact=username) me = request.user message = 'Not allowed' if request.user.is_authenticated(): is_followed = UserProfile.objects.toggle_follow(me, user_to_toggle) request.session['followed'] = is_followed return Response({'followed': is_followed}) return Response({'message': message}, status=400) The urls.py: urlpatterns = [ url(r'^(?P<username>[\w.@+-]+)/$', UserDetailAPIVIew.as_view(), name='user-posts-api'), url(r'^(?P<username>[\w.@+-]+)/follow/$', FollowToggleAPIView.as_view(), name='follow-api'), ] The only problem is that the value of (is_followed) displayed on the api seems to be the same for all users. I am certainly not following/unfollowing all users at the same time (My logic on the FollowToggleAPIView targets a specific user by his username). I want to know how … -
Django how to fetch related objects with a join?
My models are similar to the following: class Reporter(models.Model): def gold_star(self): return self.article_set.get().total_views >= 100000 class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) total_views = models.IntegerField(default=0, blank=True) Then in one of the templates I have this line: {% if r.gold_star %}<img src="{% static 'gold-star.png' %}">{% endif %} Obviously django sends as many queries as there are reporters on the page... Ideally this could be just one query, which would select reporters by criteria and join appropriate articles. Is there a way? -
except for one form, all the other are deleted when i save
when I save inscription.coso1_id, the inscription.corso2_id is deleted. when I save courses1, courses2 must be unchanged sorry for my horrible English views.py: def edit_iscrizioni(request, corso_id): corsi = Corso.objects.filter( pk=corso_id) fasca = Corso.objects.get( pk=corso_id) tabella= Iscrizione.objects.filter(user=request.user) iscrizione=get_object_or_404(Iscrizione, pk=tabella) if request.method == "POST": form = IscrizioneForm(request.POST, instance= iscrizione) if form.is_valid(): iscrizione = form.save(commit=False) iscrizione.user = request.user iscrizione.published_date = timezone.now() if fasca.f1: iscrizione.corso1_id= corso_id if fasca.f2: iscrizione.corso2_id= corso_id form.save() return redirect('privata') else: form = IscrizioneForm(instance= iscrizione) return render(request, 'corsi/edit.html', {'form':form, 'corsi':corsi}) model.py class Corso(models.Model): titolo = models.CharField(max_length=100) studenti_referenti= models.CharField(max_length=100) f1= models.BooleanField(default=False) f2= models.BooleanField(default=False) -
Perform action only when m2m_changed signal is not triggered
I have two models: User and HoursConfig and I have a Django ManyToMany relationship between them in my models.py file. I have also a m2m_changed signal to perform an action only when the ManyToMany relationship has changed. My question is: Is there any way to perform an action only when the User object has been saved and the m2m_changed signal has not been triggered?. from django.db import models from django.db.models.signals import m2m_changed from django.dispatch import receiver class User(models.Model): full_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) associated_hours = models.ManyToManyField('HourConfig', blank=True) cost_per_hour = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal('0.00')) class HourConfig(models.Model): priority = models.IntegerField(unique=True) name = models.CharField(max_length=100) start_time = models.TimeField('Start time') end_time = models.TimeField('End time') @receiver(m2m_changed, sender=User.associated_hours.through) def update_costs(sender, instance, action, reverse, model, pk_set, **kwargs): if action == 'post_add' or action == 'post_remove': update_costs_function_one() This is an example of what I want to accomplish. Obviously Django does not have a m2m_not_changed signal: @receiver(m2m_not_changed, sender=User.associated_hours.through) def update_costs(sender, instance, action, reverse, model, pk_set, **kwargs): if action == 'post_add' or action == 'post_remove': update_cost_function_two() -
Running Django migrations in a multi-container Docker setup
Is it safe to allow multiple instances of a Django application to run the same database migration at the same time? Scenario description This is a setup where a multiple instances of a Django application are running behind a load balancer. When an updated version of the Docker container is available, each of the old Docker images are replaced with the new version. If new Django migrations exist, they need to be run. This leads me to the question: is it safe to allow multiple containers to run the migration (python manage.py migrate) at the same time? I have two hypothesis about what the answer to this question might be. Yes it is safe. Due to database level locking, the migration's can't conflict and in the end, one migration script will run while the other reports that there are no migrations to apply. No this is not safe. The two migrations can possibly conflict with each other as they try to modify the database. -
I'm building a blog with django, but the terminal is saying: cannot import name Post
Here is what the terminal says: File "/Users/carlosecharte/makeblog/blogone/posts/admin.py", line 8, in <module> from .models import Post ImportError: cannot import name Post ---------------------------------[:----------------------------- This is what is in my models.py file # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Post(models.Model):pass title = models.CharField(max_length=120) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_ad=True) def__unicode__(self): return self.title This is my admin.py file: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin # Register your models here. from .models import Post admin.site.register(Post) How can I get the post app to go to my admin dashboard? Basically how can I get it to import properly? -
token not being sent in pre-flight request Ionic2
I am working on an app in Ionic 2 using DRF as API service. For authentication purpose I am using JWT. I am sending auth token with each request as Authorization: jwt [token]. In Postman, API is working fine. Now when I am testing it in browser it is not working and I figured out that it is probably not working because the JWT auth token is not being sent in the OPTIONS request as a pre-flight. So how do I tackle this problem. -
Using query set to filter displayed models
I am still very new to Python and Django. I have a custom user model. I want to display only model data that was created by a specific user. I have tried the following, but does not work. Please understand I am still learning. Model class Company(models.Model): user = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=265) def __str__(self): return self.name def get_absolute_url(self): return reverse('nodisoapp:home') View class CreateCompany(LoginRequiredMixin, generic.CreateView): login_url = '/scrty/login/' form_class = forms.Companyform template_name = 'nodiso/create_company.html' def form_valid(self, form): response = super(CreateCompany, self).form_valid(form) self.object.user.add(self.request.user) return response def get_queryset(self): self.user = get_object_or_404(models.Company,user) return models.Company.filter(user=self.user) Template {% if company_list %} <h1>Please select your company</h1> <ul> {% for company in company_list %} <li>{{company.name}}</li> </ul> {% endfor %} <button type="button" class="btn btn-info" href="{% url 'nodisoapp:createcompany' %}">Create New Company</button> <a href="{% url 'nodisoapp:createcompany' %}">create</a> {% else %} <h1>You have no companies</h1> <a href="{% url 'nodisoapp:createcompany' %}">create</a> <button type="button" class="btn btn-info" href="{% url 'nodisoapp:createcompany' %}">Create A Company</button> {% endif %} I appreciate the help -
Mixins for Permissions Django REST ListCreateAPIView
I'm sorry if I may have wrong code but I havent really been doing django rest much. I want to detect permissions from django's built in User model. I added a permission to a user model but for some reason has_perm doesn't work. I instead use user_objects.all() and detect if the permission object is there. I want to return an error 400: Unauthorized if the user does not have permission. Heres my current solution(not working): class ProgramListCreateView(PermissionRequiredMixin,ListCreateAPIView): permission_required = Permission.objects.get(name="Can CRUD") permission_classes = (IsAuthenticated,) queryset = Program.objects.all() serializer_class = ProgramSerializer def check_user(self,request): if self.permission_required in request.user.user_permissions.all(): return True return Response(status=400) when I send a json with the user token without the permission, it still creates the object Heres my mixin: class PermissionRequiredMixin(object): user_check_failure_path = 'auth_login' permission_required = None def check_user(self, user): return user.has_perm(self.permission_required) note: has_perm always returns false for some reason even if I add it using user.user_permissions.add(permission_object) -
Use celery with Django-regristration-redux to email users on signup
I'm using django-registration-redux for registration and wandering where I can add celery into it so it doesn't block and hold up the page when a user signs up? Thanks -
Django access to database from another process
I create a new Process from django app. Can i create new record in database from this process? My code throws exception: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Create Modelformset with a form for all objects of another Model
I have the following two models: class Category(models.Model): name = models.CharField(max_length=64) class Budget(models.Model): category = models.ForeignKey(Category) month = models.DateField() amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) I want to create a modelformset for all categories for a given month, with only the amount editable. My current solution is to get all budgets, and then get all categories that are not yet referenced in a budget for that month and then use a modelformset with the budgets as the queryset and the remaining categories as a dict as initial values. budgets = Budget.objects.for_month(month) ids = [budget.category_id for budget in budgets] # unassinged categories categories = [{'category': c} for c in Category.objects.exclude(id__in=ids)] BudgetFormset = modelformset_factory(Budget, fields=('amount', 'category'), extra=len(categories)) context['form'] = BudgetFormset(queryset=budgets, initial=categories) It works but has a couple of drawbacks: I have to add the category to the form, otherwise I have to write more code to check the ids of the inputs I didn't find a nice way to display the category in the template. I don't want to display the input for the category but instead just display the text for the selected option. Do you know a better approach to this? I also don't want to save budgets to the database … -
How to change a default looking forget password template in django
plz note the below codings! urls.py url(r'^reset-password/', auth_views.PasswordResetView.as_view(template_name='frgt_pswd.html'), name='reset_password'), url(r'^reset-password/done/', auth_views.PasswordResetDoneView.as_view(template_name='pswrd_sent.html'), name='reset_password_done'), url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>,+)/', auth_views.PasswordResetConfirmView.as_view(template_name='enter_new_pswd.html'), name='password_reset_confirm'), url(r'^reset-password/complete/$', auth_views.PasswordResetCompleteView.as_view(template_name='pswd_reset_cmplte.html'), name='password_reset_complete'), As you can see the above code, i have added the templates which i wanted too! But only first page is appearing. HTML code <fieldset class="module aligned"> <div class="form-row field-email"> <label for="id_email">Email address:</label> <input type="email" name="email" maxlength="300" required id="id_email" /> </div> <input type="submit" value="Reset my password" /> </fieldset> Please help! -
How to login a user during a unit test in Django REST Framework?
This is my DRF view: @api_view(['GET']) @permission_classes([IsAuthenticated]) def check_user(request): user = request.user # use user object here return JSONResponse({}) And this is my unit test for said view: class CheckUserViewTest(TestCase): def test_check_user(self): user = User.objects.create_user('username', 'Pas$w0rd') self.client.login(username='username', password='Pas$w0rd') response = self.client.get(reverse('check_user')) self.assertEqual(response.status_code, httplib.OK) But I always get a 401 UNAUTHORIZED response from my view. I have logged in the user in my test. What am I doing wrong? -
How to get FormPreview from Django FormTools to work?
I have tried to create a minimal working example of FormPreview of Django FormTools, but it did not work. forms.py This is a very simple form. from django.forms import CharField, Form, Textarea class TextForm(Form): text = CharField(widget=Textarea) preview.py This is with slight adjustments just copied from the documentation. It is of curse incomplete but I did not changed it because I did not even got to a preview page of any kind. from django.http import HttpResponseRedirect from formtools.preview import FormPreview class TextFormPreview(FormPreview): def done(self, request, cleaned_data): # Add stuff later, once I get to a preview. return HttpResponseRedirect('/') urls.py Here must be some mistake, but I don't know how it should be correct. Should I remove the first URL? How does FormPreview know what the correct view to use is? from django.conf.urls import url from django import forms from .forms import TextForm from .preview import TextFormPreview from . import views urlpatterns = [ url(r'^$', views.textform), url(r'^post/$', TextFormPreview(TextForm)), ] views.py My simple views.py. from django.shortcuts import render from .forms import TextForm def textform(request): if request.method == 'POST': form = TextForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] print(text) if request.method == 'GET': form = TextForm context = { 'form': form } return render(request, … -
Check if user is authenticated with django TokenAuthentication
I'm trying to develop a REST API with DRF that uses TokenAuthentication. This will be used in an android app. I was able to authenticate a user and retrieve it's token. The problem I'm having now is with the following view: @csrf_exempt def foo(request): if request.method == 'GET': if request.user.is_authenticated(): ... do stuff ... return HttpResponse(data, "application/json") else: return HttpResponse(status=401) Basically the user should be authenticated in order to receive the data, otherwise he will receive a 401 response. I'm making a GET request to the proper url with the following parameters in the Header: content-type : application/json authorization : Token <user token> Which is basically what I'm doing for other Viewsets (this is not a Viewset) I have - and it works. In this case it's always sending the HTTP response with 401 code (user isn't authenticated). I can't figure out if the problem is with the Header values I'm passing or if this is not the proper way to check if the user is authenticated. Edit: if I do: "print request.user" i get AnonymousUser Thanks! -
what is the difference between Django form and html form
I am working my django projects based on html form submission method . But recently, I came to know that there exist django forms. Please let me know what is the difference between them. -
Django displaying filtered model instance objects in views and html templates
I believe my notification system is setup correctly. I have a model for each notification that gets generated (a like, a comment), and in the view I am passing in all that info and filtering it depending on if the currently logged in user matches up with who each notification is directed at. Then in the template I have a loop that should display all the instances that are returned. However, while I know there are instances that should be shown, nothing is showing up on the site. I am not getting any errors, just nothing shows up. Here is my model: class UserNotification(models.Model): fromUser = models.ForeignKey(User,related_name='user',null=True) post = models.ForeignKey('feed.UserPost',related_name='post') toUser = models.CharField(max_length=6,default='user') timestamp = models.DateTimeField(auto_now_add=True) notify_type = models.CharField(max_length=6) read = models.BooleanField(default=False) def get_absolute_url(self): return reverse('notify:user_notifications') def __str__(self): return str(self.fromUser) View that creates notification instance (I know this works because new instances are shown in the admin): class LikePostToggle(RedirectView): def get_redirect_url(self,pk): obj = get_object_or_404(UserPost,pk=pk) user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) notification = UserNotification.objects.create( fromUser = self.request.user, toUser = obj.author, post = obj, notify_type = "like", ) return obj.get_absolute_url() View that should be showing the notification instances: User = get_user_model() class UserNotifications(LoginRequiredMixin, ListView): login_url = … -
Invalid column name 'Last_Changed_Date'
Hello I'm currently using Python 3.6 and Django 1.11, when defining my view as: def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) applicationdetail = QVReportAccess.objects.get(ntname='HCA\HFA9592') print(applicationdetail) args = {'user':owner.formattedusername, 'user':owner, 'applicationaccess':applicationdetail.report_name} return render(request, 'accounts/profile.html', args) I'm greeted with the following error message, why doesn't Django like the name Last_Changed_Date: ProgrammingError at /account/profile/ ('42S22', "[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'Last_Changed_Date'. (207) (SQLExecDirectW)") Request Method: GET Request URL: http://127.0.0.1:8000/account/profile/ Django Version: 1.11.5 Exception Type: ProgrammingError My model is a pre-existing database table defined as: class QVReportAccess(models.Model): user_status = models.CharField(db_column='User_Status', max_length = 20) # Field name made lowercase. ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='NTName', max_length=7,primary_key=True, serialize=False) # Field name made lowercase. report_name = models.CharField(db_column='Report_Name', max_length=50, blank=True, null=True) # Field name made lowercase. report_name_sc = models.CharField(db_column='Report_Name_SC', max_length=30, blank=True, null=True) # Field name made lowercase. datareduce_report_code = models.IntegerField(db_column='DataReduce_Report_Code', blank=True, null=True) # Field name made lowercase. role_based_id = models.IntegerField(db_column='Role_Based_ID', blank=True, null=True) # Field name made lowercase. report_id = models.OneToOneField(QvReportList,db_column='Report_ID', max_length=100, blank=True, null=True) # Field name made lowercase. report_group_id = models.IntegerField(db_column='Report_Group_ID', blank=True, null=True) # Field name made lowercase. report_access = models.CharField(db_column='Report_Access', max_length=50, blank=True, null=True) # Field name made lowercase. sr_datareduce_summary_code = models.CharField(db_column='SR_DataReduce_Summary_Code', max_length=10, blank=True, null=True) # Field name made lowercase. sr_datareduce_patient_code = models.CharField(db_column='SR_DataReduce_Patient_Code', max_length=10, blank=True, null=True) # Field name …