Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ValueError - not enough values to unpack (expected 2, got 1)
Getting the error in the title when I try to go on my listing_public page, can't figure out why. views.py def listing_public(request, pk): listing = get_object_or_404(BuyerListing, pk) return render ( request, 'listing_public.html', context={'listing':listing} ) urls.py url(r'^listing/(?P<pk>\d+)/$', views.listing_public, name='listing_public'), Template Tags {% url 'listing_public' pk=listing.pk %} This is the only other question on Stack Overflow I found regarding this error, but the sole answer didn't solve my problem. Here is the traceback. -
Restricting admin urls to already authenticated superusers in Django
I've searched around for some solutions to this, but they all focus on a single admin url. However I was wondering if there is a way to restrict ALL the admin views, not the accounts to already authenticated superusers. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')) ] What I want is urlpatterns = [ url(r'^admin/', is_superuser(admin.site.urls)), url(r'^accounts/', include('accounts.urls')) ] Or something like this that I can do in the view @user_passes_test(lambda u: u.is_superuser, login_url='allauth.account.views.LoginView') def superuser_only(request, template): return render(request, template) but still allows me to use admin.site.urls. Is there a quick and elegant way to solve this? I want all users including the superuser to authenticate through accounts app. -
Django 1.8 AttributeError("'module' object has no attribute 'commit_unless_managed'")
Seems like django 1.8 deprecated support for commit_unless_managed module. Any suggestions on what alternatives one should use ? -
Using Django Context Processors with forms
I have multiple forms to be shown everywhere in my project and hence I read that having a context_processor was the best way to do it. So, I created one inside my app and it looks something like this: def forms_processor(request): name_form = NewNameForm() work_form = NewWorkForm() address_form = NewAddressForm() context = {'name_form': name_form, 'work_form': work_form, 'address_form': work_form, } return context This works great, I can just use {{name_form}} anywhere in my templates and that renders the form. Now my question is, where do I validate the form? In my views.py or the context_processors.py? Right now my views for name_form looks something like this: def user_profile(request): if request.method == 'POST': name_form = NewNameForm(request.POST) if name_form.is_valid(): form.save() else: ctx = {'title': 'Profile', 'active_tab': 'Profile'} return render (request, 'user_profile.html', ctx) This isn't working actually, if I submit an invalid form, it just comes back to the same page and won't show a populated form. If someone could guide me or redirect me to some docs on this topic, that'd be awesome! Thanks! -
Authentication on Post DRF
I got an error on my DRF. when I try to authenticate using a post method. the token is the correct for the admin user. when I use a safe method it is sucessfull, but with the method post no, it doesn't authenticate my view class SpecialistListView(ListCreateAPIView): authentication_classes = (OAuth2Authentication,) permission_classes = (permissions.IsAdminUser,) queryset = Specialist.objects.all() serializer_class = SpecialistSerializer I don't understand why the status of the code returned is HTTP 401 Unauthorized. -
Avoid user pk in Django user edit form
I want to create a Django form to edit user information. I have: urls.py url(r'^settings/(?P<pk>[0-9]+)/', views.edit_profile, name='edit'), views.py @login_required def edit_profile(request, pk): user = get_object_or_404(User, pk=pk) if request.method == 'POST': form = UserForm(request.POST, instance=user) if form.is_valid(): form.save() else: form = UserForm(instance=user) return render(request, 'edit_user.html', {'form': form}) Like this, when a user edit its information can change pk from url and see other users information. How can I hide this pk in the url? Thanks. -
Multiple datetime fields for a model in Django
I want to create a log system to register some faults I need to handle at my work. I use Django and my models look like these: class Chan(models.Model): channelname = models.CharField(max_length=30) freq = models.FloatField(default = 0.0) def __unicode__(self): return u'%s' % (self.channelname) # timestamp object class EventTime(models.Model): since = models.DateTimeField() till = models.DateTimeField() def __unicode__(self): return u'%s' % self.since.strftime('%Y-%m-%d %H:%M') class Fault(models.Model): channel = models.ManyToManyField(Chan) description = models.CharField(max_length=200, default="-") message = models.TextField() timeevent = models.ManyToManyField(EventTime,null=True) visible = models.BooleanField() Firstly I used just one EventTime object but I soon realized I need to be able to choose several time periods because the same event could happen several times a day. So it would be too tedious to create a new record of Fault each time. So I basically needed something like this: The problem is that 'ManyToManyField' is too unhandy to use because I don't need to keep these values for other faults. So I don't know what solution I can use for it. I don't know how many time periods I need. Maybe I could add an extra Text field to my table where I would keep comma-separated datetime objects converted into a string like '2017-11-06 18:36,2017-11-06 18:37'. But … -
Create new model instance with one to one and foreign key field
Model: class BurrowedBook(models.Model): # Fields borrow_date = models.DateField() return_date = models.DateField() actual_return_date = models.DateField(null=True) # Relationship Fields book_copy = models.OneToOneField(BookCopy) burrowed_by = models.ForeignKey(Member) Save new instance: BurrowedBook.objects.create(borrow_date=borrow_date, return_date=return_date, book_copy=book_copy, burrowed_by=member) How do I save a new instance of this model? I'm having trouble with one to one field and foreign key field. -
Django - Add button to create foreign keys objects in modelforms
This is based on an old post Django: adding an "Add new" button for a ForeignKey in a ModelForm, it mentions ModelChoiceField. Is ModelChoiceField in Django 1.11? If not, what would you use instead? -
Static file error with Heroku and whitenoise - have run collect static
I redeployed an Django app to heroku, and am now getting static file issues: ValueError: Missing staticfiles manifest entry for 'css/styles.min.css' I had an error when upgrading boto (used for media files only not static files). So turned collect static off on heroku with: heroku config:set DEBUG_COLLECTSTATIC=1 After fixing the error I manually ran: heroku run python manage.py collectstatic --noinput to process the static files which produced no issues with the output: 239 static files copied to '/app/staticfiles', 263 post-processed However even though the collectstatic command worked I get the above the static files error above. I am using white noise on heroku with the production settings: `WHITENOISE_MIDDLEWARE = ('whitenoise.middleware.WhiteNoiseMiddleware', ) MIDDLEWARE = WHITENOISE_MIDDLEWARE + MIDDLEWARE WHITENOISE_MAX_AGE = 60 * 60 * 24 * 365 * 10 # 10 yrs STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'` and in requirements have whitenoise==3.3.1 I'm not clear what's causing the issue or how best to resolve as I've checked everything I can think of. -
PUT request being called more than once
I'm new to Ajax/jQuery and I am doing an assignment where I must use http method PUT to update a django model. The code I currently have works except for one issue: the PUT request is being run multiple+1 times each time I click on a new modify button and submit the form. Example via console.log: (index):121 BUTTON: Pressed modify on product ID: 87 (index):133 GET: Looped through products for ID 87 and set the values in the modal accordingly (index):153 PUT: Received put request for ID: 87 (index):121 BUTTON: Pressed modify on product ID: 88 (index):133 GET: Looped through products for ID 88 and set the values in the modal accordingly (index):153 PUT: Received put request for ID: 87 (index):153 PUT: Received put request for ID: 88 (index):121 BUTTON: Pressed modify on product ID: 89 (index):133 GET: Looped through products for ID 89 and set the values in the modal accordingly (index):153 PUT: Received put request for ID: 87 (index):153 PUT: Received put request for ID: 88 (index):153 PUT: Received put request for ID: 89 Code for ajax: // MODIFYING A PRODUCT product_ul.on("click", ".modify", function () { // On clicking modify var id = $(this).parents('li').attr('id'); // Get the PK … -
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