Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending the logged on username to Sentry in Django
Trying to send the logged on username to Sentry. If hard coded in settings, I get the expected result on the Sentry dashboard. However I can't set the username in settings. #settings.py from sentry_sdk import configure_scope with configure_scope() as scope: scope.user = {"username": "Joe Soap"} So I am not sure where I should be doing this: with configure_scope() as scope: scope.user = {"username": request.user.username} I have tried my landing view and login view. But just get my IP Address back on the sentry dashboard. #views.py @login_required def landing(request): context={} with configure_scope() as scope: scope.user = {"username": request.user.username} return render(request,'paysched/landing.html',context) Python and Django are not my home language, so my questions really are A) can I do this? B) and if so, where/how. Thanks in advance for any assistance on this. -
Django ListVIew redirect if model has no records
I have built a class PlayerListView which uses class ListView for generic display of views. class PlayerListView(LoginRequiredMixin, ListView): model = PlayerSeason template_name = 'squad/players_list.html' context_object_name = 'players' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['test'] = 'test' context['season_name'] = PlayerSeason.objects.first().season.season_name return context Normally if there are no records for the PlayerSeason model, the template display html code with zero data to display. But as my template also needs additional data, I needed to put it in 'context' using get_context_data(). context['season_name'] = PlayerSeason.objects.first().season.season_name The problem occurs when there are no records for PlayerSeason and I want to set the context data for season_name. It checks for the fields in the relation field 'season'. Because it does not exist, it returns error: AttributeError: 'NoneType' object has no attribute (logical). What I want to avoid any errors is to redirect to the url for insertion of PlayerSeason records (lets say: '/create/playerseason'. One of the solutions I tried was checking that in the get() method if PlayerSeason.objects.count(): season_name = PlayerSeason.objects.first().season.season_name else: return redirect('blog-home') What is the correct/elegant solution in this case? -
I created registration form through django forms.But its not rendring?
I am trying to create blog app with django.I created registration form with django forms.In official django documentation for get request the code is form.classname().I also coded in that way.But its returning register() missing 1 required positional argument: 'request'? from django import forms class register(forms.Form): Email = forms.EmailField(required=True) Username = forms.CharField(label='Username', max_length=100,required=True) Password = forms.CharField(widget=forms.PasswordInput(),required=True) Confirm_Password = forms.CharField(widget=forms.PasswordInput(),required=True) views.py def register(request): if request.method == "POST": form = register(request.POST) email = form.cleaned_data['email'] User_name=form.cleaned_data['User_name'] Password1=form.cleaned_data['Password1'] Password2=form.cleaned_data['Password2'] if form.is_valid(): if User.objects.filter(username=User_name).exists(): messages.info(request,'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('register') else: user = User.objects.create_user(username=User_name, password=Password1,email=email) user.save(); return redirect('/') else: messages.info(request,'Password Not Matching') else: form = register() return render(request,'register.html',{'form': form}) models.py from django.db import models from django.conf import settings # Create your models here. class Post(models.Model): title=models.CharField(max_length=100) desc=models.TextField() date=models.DateField(auto_now=True) author=models.ForeignKey(settings.AUTH_USER_MODEL, to_field="username",on_delete=models.CASCADE) Showing error:register() missing 1 required positional argument: 'request' -
Django: AttributeError: module 'todo.views' has no attribute 'delete_item'
I'm trying to make a to-do app with Django. Users can add an item and now I'm trying to implement the functionality for deleting an item. When defining the view to delete an item I get his error: AttributeError: module 'todo.views' has no attribute 'delete_item'. I checked many forums and videos and to me the code seems right. Any suggestions please? Thank you. Models: from django.db import models class TodoItem(models.Model): content = models.TextField() Views: from django.shortcuts import render, redirect from .models import TodoItem from .forms import ItemForm def delete_item(request, todo_id): item = TodoItem.objects.get(pk=todo_id) item.delete() URLs: from django.urls import path from django.views.generic import TemplateView from . import views path('delete/<todo_id>/', views.delete_item, name='delete_item') HTML: <a href="{% url 'delete_item' things.id %}"> <button class="button is-danger is-outlined">Delete</button> </a> the error message I get when I run the server: AttributeError: module 'todo.views' has no attribute 'delete_item' -
com_error "Server execution failed" for Dispatch("Photoshop.Application")
I use win32com.client.Dispatch to manage Photoshop on a Windows server, I configured the address to connect to this server and now when I send a request from my local machine to the server, win32com.client.Dispatch gets com_error (-2146959355, 'Server execution failed', None, None) When it tried to use Dispatch("Photoshop.Application"). Everything works fine on the server itself without any problem with Dispatch. (This is all used to change layers in a psd file) I have got another com_error before (-2147024891, 'Access is denied.', None, None), but fixed this problem with the help of this Code that generates error app = Dispatch("Photoshop.Application") Photoshop location: "C:\Program Files\Adobe\Adobe Photoshop CC 2015" Help please! -
Dismissing a partially filled out form in ModelFormSet with a ManytoMany field
I have a Modelformset that contains a manytomany field. The M2M field, is rendered as a ModelMultipleChoiceField. The whole thing runs fine when all forms are filled out. In short, the only user input I receive are from the checkboxes on each form of the formset. There are other fields but they are pre-filled with user data. I want to save the forms where a checkbox was selected and ignore the form that none are selected from. I was able to get the partially filled forms to pass validation so all forms are saved but I'm having a hard time writing the test that would discard the partially filled (the form that no checkboxes we're selected from) form. Models.py customer_id = models.ForeignKey(CustomerDB, on_delete=models.CASCADE, default=None) services_manytomany = models.ManyToManyField(ContractorServices, blank=True) class ContractorServices(models.Model): service_parent = models.ForeignKey(User, on_delete=models.CASCADE, default=None) service_name = models.CharField(max_length=150, null=True, blank=True) archive = models.BooleanField(default=False, null=True) def __str__(self): return self.service_name forms.py services_manytomany = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=ContractorServices.objects.all() ) def __init__(self, user, *args, **kwargs): super(AddJob, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.form_show_errors = True self.helper.form_tag = False self.fields['services_manytomany'].required = False if user is not None: self.fields['services_manytomany'].queryset = ContractorServices.objects.filter(service_parent=user) class Meta: model = Jobs_DB fields = {'services_manytomany', 'frequency'} Relevant view.py code formset = … -
Python: .pop behaves different between same and different line
Can someone explain to me why these two code snippets behave differently? Here I get the expected output {datetime.date(2019, 6, 18): 12300} events_sales_gross_last_7_days = events_sales_gross_last_7_days_incl_today.get(event.pk, {}) events_sales_gross_last_7_days.pop(timezone.now().date(), 0) print(events_sales_gross_last_7_days) The next snippet however only gives me back 'int' object has no attribute 'get'. events_sales_gross_last_7_days = events_sales_gross_last_7_days_incl_today.get(event.pk, {}).pop(timezone.now().date(), 0) print(events_sales_gross_last_7_days) -
Django admin area causing Server Error (500) when logging in
I made a django application which I'm trying to deploy. It's a very small website on my home network on a Raspberry Pi. I have a domain pointed to the IP. When I set DEBUG to False and try to log into the admin area, it causes a "Server Error (500)". My settings.py ALLOWED_HOSTS = ["my domain", "my ip", "localhost", "127.0.0.1"] I am able to use the website and log view it remotely. Even when i put "*" it dos not work. -
Django view only renders first URL
I have the following code in my Django applicaton: View.py def Chart(request): #fusionchart code return render(request, 'dash.html', {'output' : column2D.render(),'output2' : doughnut3d.render(),'output3' : area2D.render()}) def view_name(request): #calculation code return render(request, 'dash.html', {'today': today}) def default_map(request): #map built code return render(request, 'dash.html', { 'mapbox_access_token': mapbox_access_token }) url.py urlpatterns = [ url(r'^$', views.Chart, name = 'Chart'), url(r'^$', views.view_name, name = 'view_name'), url(r'^$', views.default_map, name="default"), ] The issue that I am currently having is that the urlpatterns only show/render what is done in the first def (in this case def Chart) and skip the other two defs. How can I make sure that Django takes into account all three defs and renders all three of them on the same page? -
Django-Rest-Framework CreateAPIView not working
I am trying to implement a simple viewset from django-rest-framework, everything is working OK except for the Create view. The ulr (http://127.0.0.1:8000/api/create/) is loaded with the form to input data but when I hit PUT the data is not loaded in database. Terminal shows the following error: [19/Jun/2019 14:15:29] "GET /api/create/ HTTP/1.1" 404 10318 Not Found: /api/create/ I am following this tutorial to learn to integrate django and react. I've previously tried to implement CRUD views separately but got a circular reference error. I suppose there must be some sort of error with url definitions but I just can't figure out what is wrong. API urls.py: from articles.api.views import ArticleViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', ArticleViewSet, base_name='articles') urlpatterns = router.urls API views.py: from rest_framework import viewsets from articles.models import Article from .serializers import ArticleSerializer class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer queryset = Article.objects.all() API serializer: from rest_framework import serializers from articles.models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content') Project urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/', include('articles.api.urls')), ] With this code, when I access the List view the form to … -
saving to django model gives null error even though model field has default value
When saving to a django model via a dict which does have the key and value {...,'type': None,...} the model field is type = models.CharField(max_length=3, choices=Type.CHOICES, default=Type.EITHER) However when trying to save I get an error: django.db.utils.IntegrityError: null value in column "type" violates not-null constraint Does the ORM in django not try to use the default value if a None is specified directly? How best should this be handled? -
how do i link my listview and detailsview in django templates such that when i click the list it then shows me the details
"im setting up my django-templates of a project o show schoolevents and job listings, i want its response to show me details of a list once i click the item on the list -can some one help am a newbie tp programming" i've tried adding slugfield to my models, changed the urls a couple of time but still i'm failing to reach my target models.py class Events(models.Model): title = models.CharField(max_length=80) host = models.CharField(max_length=80) venue = models.CharField(max_length=80) event_image = models.ImageField() details = models.TextField() posted_at = models.DateTimeField(auto_now_add=True) start_time = models.DateTimeField() end_time = models.DateTimeField() contacts = models.CharField(max_length=80) sponsors = models.CharField(max_length=80, null=True, blank=True) slug = models.SlugField(max_length=150, null=True, blank=True) class Meta: ordering = ('-posted_at',) form.py class EventsForm(forms.ModelForm): class Meta: model = Events fields = ( 'title', 'host', 'venue', 'details', 'start_time', 'end_time', 'contacts', 'sponsors', ) views.py class CreateEventsView(LoginRequiredMixin, CreateView): model = Events message = _("Your Event has been created.") form_class = EventsForm template_name = 'posts/create_events.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse('list_events') class EventsListView(ListView): model = Events form_class = EventsForm context_object_name = 'all_events' template_name = 'events_list.html' success_url = reverse_lazy('list_events') def get_queryset(self): qs = super(EventsListView, self).get_queryset() return qs class DetailEventsView(DetailView): model = Events def render_to_response(self, context, **response_kwargs): if self.request.is_ajax(): return … -
"Cannot read property 'prefix' of undefined" javascript error in Django inlines.js
After updating Django to version 2.1.9 (from 1.9.8) I am receiving "Cannot read property 'prefix' of undefined" javascript error on Django admin page when there are inline models. The problem is in function tabularFormset in inlines.js file. This function takes two parameters: function(selector, options). options here should have prefix param but it appears that options are undefined. It looks like Django custom functions doesn't append selector as a first param, so options are first param. In result options param here is undefined. Does anyone know what the problem might be here? -
media not displayed in django deploy using nginx + gunicorn service
I am deploying a django app in a VPS (debian 9) using Nginx and gunicorn service. Everything works as expected but images uploaded by the user in media file are not displayed, 404 (not found). When I use Debug=True images are displayed, Static file works correctly in development and production. To run this app I have created a webuser without sudo rights and a group called webapps. Since it sems that nginx can't see the media I have changed the group to www-data, but still it doesn't work. There is a similar issue here but without accepted answer. Any help will be much appreciated. Bellow some important configurations: (web_env) webuser@:~/web_project$ ls -la total 72 drwxrwxr-x 10 webuser www-data 4096 Jun 11 20:30 . drwxr-xr-x 3 webuser webapps 4096 Jun 10 17:15 .. drwxr-xr-x 6 webuser webapps 4096 Jun 10 17:15 blog -rw-r--r-- 1 webuser webapps 655 Jun 10 17:15 environment.yaml drwxr-xr-x 2 webuser webapps 4096 Jun 10 17:15 .idea drwxr-xr-x 2 webuser webuser 4096 Jun 11 17:28 logs -rwxr-xr-x 1 webuser webapps 631 Jun 10 17:15 manage.py drwxrwxr-x 3 webuser www-data 4096 Jun 10 17:15 media -rw-r--r-- 1 webuser webapps 14417 Jun 10 17:15 posts.json -rw-r--r-- 1 webuser webapps 229 … -
How to Implement a Location Search / Maps in a Django Application
I would like to get some inputs on how should I go about proceeding to achieve the Following. I want to implement a Web App in Django which will look/search for 'My Supermarket Chain' within 'X KM' of my current location, and choose it and look for products available there. As an Example, let's make all the Dominos Chain as 'My Supermarket'. I have already implemented the Part in which the Products in each Stores are set. How would I go about achieving this? Let's say I have my Store Model as follow: class Store(models.Model): name = models.CharField() location = ?? Should I be adding the Logitude / Latitude of a Dominos Chain to the location field? or Should I use an API like Google Maps and change the things there? I am totally blank on how I should go about / learn to achieve this. Please suggest what all things I would need to learn and how to Apply those so that I can learn it and do it. -
UnboundLocalError: local variable 'r' referenced before assignment (Django)
I want to reference the value of an item company_id in a object company_obj created from a RESTful API call cwObj.get_company(company) and then pass that value to another API call cwObj.get_sites(company_id) and then return the object. However, I am getting an UnboundLocalError when I attempt to pass company_id to the API call. Through debug, I can see that company_id has the desired value so I am not sure why I am unable to then create another object using said value. Does this not mean the variable is indeed assigned? If not, what is the best practice to assign the variable before it reaches the cwObj.get_sites() call? Please let me know if any more information is needed, thanks! views.py def new_opportunity_location(request): company = request.GET.get('selected_company') company_obj = cwObj.get_company(company) company_id = company_obj[0]['id'] sites = cwObj.get_sites(company_id) context = {'sites': sites} return render(request, 'website/new_opportunity_location.html', context) -
Django - Make 3rd-party API call and django can no longer find base.html
I am trying to make a call to a third-party API in my Django app, more specifically in a views.py. Once I make this call, Django fails to find the template base.html. Essentially this is what's happening: user searches for a term in a search form the request gets sent to my view the view has an if statement to handle when the user is making a GET request, so this piece of logic handles the request the view makes a call to a separate function search_by_jobsite() written by me inside search_by_jobsite(), a call to a third-party API is made, and I pass the location of a .pkl file to the API. The location is /webapp/camera_search/api/pickle/config.pkl. Everything is fine and search_by_jobsite() retrieves the necessary information It returns the information back to the view, and the view goes on to define the context dictionary and attempts to render(request, 'siren_search.html', context). However, this is where it fails. The first line in siren_search.html is {% extends 'base.html' %}, so it starts looking for base.html but it's looking in the wrong directory. It is searching for base.html in /webapp/camera_search/api/pickle/ when base.html is located in /webapp/webapp/templates/base.html. For some reason when django goes to the pickle/ … -
django modelForm not validating added foreign key
I have a modelForm where I overwritte the init method to provide a predefined value from a FK. However when validating the form with the method is_valid() it fails as it says "Palabras" already exists but is not taking in consideration the FK "fk_funcion" as both are PK. Models.py class Palabras(models.Model): fk_funcion = models.ForeignKey(Funcion, related_name='funcion', on_delete=models.CASCADE) palabra = models.CharField(max_length=30, unique=True) porcentaje = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) class Meta: unique_together = ("fk_funcion", "palabra"), def __str__(self): return self.palabra Forms.py class PalabraForm(forms.ModelForm): class Meta: model = Palabras fields = ('palabra','porcentaje', "fk_funcion") def __init__(self, *args, **kwargs): fk_funcion = kwargs.pop('fk_funcion','') super(PalabraForm, self).__init__(*args, **kwargs) self.fields['fk_funcion']=forms.ModelChoiceField(queryset=Funcion.objects.filter(id=fk_funcion)) Views.py def create_palabra(request, pk_funcion): data = dict() if request.method == 'POST': form = PalabraForm(request.POST,fk_funcion=pk_funcion,,initial={'fk_funcion':pk_funcion}) #I have tried with and without the initial value if form.is_valid(): #Some action What do I have to modify in order to make the form to validate both "palabra" and "fk_funcion" in the modelForm. Thanks -
Store time stamps to database(Please read the description)
I am creating a Django web based application for freelancers ,that they would be paid for number of hours they have worked on a project and also a weekly report is to be generated for weekly work and for that i need to work with time stamps so how do i implement it ? I want to create a button of start timer and stop timer ,which records the time stamps of start timer and end timer? I have a User model which is extended to Freelancer and person who hires Freelancer ,How do i implement this? Where do i edit the model of time stamps? I have this model from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_freelancer = models.BooleanField('Freelancer status', default=False) is_hirer = models.BooleanField('Hirer status', default=False) class Freelancer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) hourly_rate = models.PositiveIntegerField(default=10) education = models.TextField(default='asia') professional_bio = models.TextField(blank=True, null=True) professional_title = models.TextField(blank=True, null=True) location = models.CharField(max_length=10, blank=True, null=True) Address = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) postal_code = models.PositiveIntegerField(blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) class Hirer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) hourly_budget = models.PositiveIntegerField(blank=True, null=True) project_title = models.CharField(max_length=100, default='hi') project_description = models.TextField(blank=True, null=True) job_category = models.CharField(max_length=100) professional_bio = models.TextField(blank=True, null=True) professional_title … -
Custom FilterSet doesn't filter by two fields at the same time
I wrote custom FilterSet to filter queryset by two fields but it doesn't work properly when it's filtering on two fields at the same time. my FilterSet: class EventFilter(filters.FilterSet): values = None default = None category = filters.ModelMultipleChoiceFilter( queryset=EventCategory.objects.all(), ) interval = filters.CharFilter( method='filter_interval' ) class Meta: model = Event fields = ('category', 'interval') def filter_interval(self, queryset, name, value): if self.request.query_params.get('current_time'): try: interval = getattr(self, f'get_{value}_interval')() interval = list(map(lambda date: self.to_utc(date), interval)) return self.queryset.filter(Q(status=Event.STARTED) | (Q(status=Event.NOT_STARTED, start_at__range=interval))) except Exception as e: pass return queryset APIView: class ListEventsAPIView(generics.ListAPIView): serializer_class = ListEventsSerializer filter_class = EventFilter search_fields = 'title', filter_backends = filters.SearchFilter, DjangoFilterBackend def get_queryset(self): return Event.objects.filter(Q(status=Event.STARTED) | (Q(status=Event.NOT_STARTED) & Q(start_at__gte=date))) Here is generated SQL when I'm trying to filter only by category: SELECT "*" FROM "events" WHERE (("events"."status" = 'started' OR ("events"."status" = 'not_started' AND "events"."start_at" >= '2019-06-19T13:24:26.444183+00:00'::timestamptz)) AND "events"."category_id" = 'JNPIZF54n5q') When I'm filtering on both: SELECT "*" FROM "events" WHERE (("events"."status" = 'started' OR ("events"."status" = 'not_started' AND "events"."start_at" >= '2019-06-19T13:24:26.444183+00:00'::timestamptz)) AND ("events"."status" = 'started' OR ("events"."start_at" BETWEEN '2019-06-19T07:16:48.549000+00:00'::timestamptz AND '2019-06-30T20:59:59.000059+00:00'::timestamptz AND "events"."status" = 'not_started'))) -
Querying the data from data-lake gen 2 to python backend
I have python (Django) backend which needs to query the data from data-lake gen 2 based on the HTTP requests and provide the result as API to the end user interactively. How could I solve this use case? I am coming from database background and not so familiar with all the data analytics solutions provided by the cloud. The data is distributed in lots of structured TSV files. I decided to go with the data lake to utilize a few features such as partition and fast processing. I was planning to use U-SQL but since it only provides the result in the output file which is not so efficient in my case. Any better approach to solve this issue? Thanks in advance. -
How call specified item of model in html?
having a model named books, we can get name of second book by books.2.name, and name of 3rd book by books.3.name so, how can get books.i.name, where i is specified by user? -
How to use a single django codebase across multiple (and isolated) server installs and multiple databases
We would like to use the same django codebase to offer our service to multiple companies where each company would have their own install, own database completely isolated from the rest. Looking to find the best strategy to do this. We are at the planning stage. However we have identified the following requirements and potential problems/extra workloads. Requirements 1.) The codebase should be identical. 2.) Each install should have its own database which stores company specific records such as employee details, and also content to be delivered to the front end (copy and such like). Each company must have its own database. Potential problems 1.) Currently when we make database structural changes, we apply these using the django migration system. However, we currently have one install with hundreds of migrations, a new install would not need all of these, only the current version of the models. So we'd end up having to keep track of and produce and version control multiple different sets of migrations. How best to approach this. 2.) Some of the migrations we have in our project are data only, and they are simply not relevant to any new installations. It's also possible that going forward we … -
Django: How to not return all model fields
I'm using a Django system where each model has an associated serializer (pretty standard). In one model, the serializer is as follows: class ThingSerializer(ModelSerializerWithFields): class Meta: model = Thing fields = "__all__" and a model: class Thing(models.Model): class Meta: ordering = ("a", "b") thing_id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False) a = models.FloatField(null=True, blank=True, default=None) b = models.FloatField(null=True, blank=True, default=None) I want to implement a system that: if field a of Thing is not null, then field b is returned (on a GET request, for example), and if a is null then b is not returned. How (and where) can I do this? -
How to Filter by Post Arguments in ListView
I am trying to create a form in my ListView which POSTs to the ListView and filters by the POSTed attributes. This is in a Django 2.1 project. I have tried passing both self and request argunments to the post function but I am receiving the Exception below e.g. def post(self, request): results in a TypeError exception: post() takes 1 positional argument but 2 were given If I try to solve the error by removing one of the parameters so that only self is passed to the post() def post(self) function I receive the following TypeError exception: post() takes 1 positional argument but 2 were given Despite the fact that only self has been passed. I have tried only passing request and that results in the same thing. Lots of examples online show def post(self, request, *args, **kwargs) This results in the obvious exceptions of: too many values to unpack (expected 2) Removing all arguments results in a TypeError: post() takes 0 positional arguments but 2 were given class thing_dashboard(ListView): ''' All Orders processed ''' template_name = 'thing/orders_dashboard.html' paginate_by = 25 def post(self, request): queryset = Order.objects.all().order_by('-ordered_date') rejected = self.request.POST.get('rejected') if rejected == 'False': queryset = Order.objects.filter(state='rejected') return queryset return …