Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to authenticate valid super user or not in django
I have created a superuser in Django. Is there any way I can authenticate the superuser credentials using a REST API? or Do I need to write a scripted REST API? If my question is too broad please let me know. I will update my question. Regards -
Django perform_create conditional creation
I can create a Product based on JSON data. I would like to add a condition so then if a Product already exists with the same name I don't create anything and my view returns the existing Product. For the creation no problem, the Product is set correctly and the view returns the data (I checked in DB and it's here). But when I try to create a second product with the same name I have an error (Here I use the exact same JSON). View : class ProductCreate(generics.CreateAPIView): """ Create a new product """ permission_classes = (permissions.IsRequestAllowed,) serializer_class = ProductSerializer def perform_create(self, serializer): product = product_service.get_product_from_name(serializer.validated_data['name']) if not product: LOG.debug('Creating Product from JSON data : {} '.format(serializer.validated_data)) serializer.save() else: LOG.debug('{} already exists, JSON data : {} '.format(product, serializer.validated_data)) Serializer : class ProductSerializer(serializers.ModelSerializer): class Meta: # pylint: disable=too-few-public-methods model = Product fields = ('id', 'actor', 'brand', 'creation_date', 'description', 'ean_code', 'image', 'internal_code', 'name', 'price_unit', 'product_group', 'url',) Model : class Product(models.Model): actor = models.ForeignKey(Actor, related_name='products', on_delete=models.CASCADE) brand = models.CharField(max_length=200, blank=True) creation_date = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=1000, blank=True) ean_code = models.CharField(max_length=200, blank=True) image = models.CharField(max_length=400, blank=True) internal_code = models.CharField(max_length=200, blank=True) name = models.CharField(max_length=200, blank=False) price_unit = models.CharField(max_length=200, blank=True) product_group = models.ForeignKey( ProductGroup, related_name='products', … -
NOT NULL constraint failed: auth_user.username when i went to pass user in post
when i went to pass user in post the error NOT NULL constraint failed: auth_user.username is prodecte this is my code class Enseignant(models.Model) : user=models.OneToOneField(User,on_delete=models.CASCADE) sexe =models.CharField(choices=SEXE,max_length=25) numero_telephone=models.CharField(max_length=255,blank=True,null=True) def __str__(self): return self.user.first_name class SupprimerEnseignantForm(forms.Form): enseignant=forms.ModelChoiceField(Enseignant.objects,widget=forms.Select( attrs={ 'class':'form-control' } )) form2=SupprimerEnseignantForm(request.POST or None) -
How do I open a session to keep login credentials through multiple http requests?
I'm trying to make Http requests using Angular 6. My login call works, but when I try to get use a different call, it tells me I'm not logged in. I think it's because the login isn't valid, but I'm not sure how I can keep it valid for subsequent calls. Here is the code appComponent file: ngOnInit(): void { this.data = this.login.getData(); this.farmAccessdata = this.getFarmAccess.farmAccess(); } And here is the login service: export class loginService { base_URL = "..." login = { username: username, password: password } constructor(private http: HttpClient) { } getData(){ return this.http.post(this.base_URL + "...", JSON.stringify(this.login)) .subscribe(data => { console.log("We got ", data) }) } And the farmaccess service: export class GetFarmAccessService { data = {}; baseURL = "..." constructor(private http: HttpClient) { } farmAccess(){ return this.http.get(this.baseURL + "...") .subscribe(data => { console.log("We got ", data) }) } When I run the farmAccess service, it gives me an error saying I'm not logged in. The login framework on the server side is cookie based auth, powered by django user module. How can I fix this? Thanks. -
Django CMS modify plugin for installed app via pip
I would like to know how to achieve the following for apps installed via pip: Show only specific fields when editing the plugins in the cms Override the verbose name of some of the models showed when editing the plugins Restrict the length of the fields Add new fields to the models For reference, my app installed via pip is aldryn-newsblog. Would be great if any of this would be possible. Thanks a lot in advance! -
How to fix circular importing?
It seems I have a circular importing error. I currently just struggling to fix it. Does anyone know what I should do? In my models.py, containing ReservedItems & Order: def reserveditem_pre_save_receiver(sender, instance, **kwargs): if not instance.order_reference: instance.order_reference = unique_order_reference_generator() In my utils.py from lumis.utils import get_random_string from .models import Order, ReservedItem def unique_order_reference_generator(): new_id = get_random_string(length=10) reserved_item = ReservedItem.objects.filter( order_reference=new_id ).exists() order = Order.objects.filter(order_reference=new_id).exists() if reserved_item or order: return unique_order_reference_generator() else: return new_id -
How to prevent django tests from showing sys.stdout messages?
My problem is that since I have added logging to my django app when I run my unit tests all my log messages show in the console. I use nose as test runner. Its usual behaviour was to capture sys.stdout, only show console output if a test failed and show it at the end. I used to have this output when running my tests: ........ Ran 8 tests in 0.876s OK Destroying test database for alias 'default'... This is the output I am getting now when I run python manage.py test accounts: ...log message .log message ....log message Ran 8 tests in 1.034s OK Destroying test database for alias 'default'... This has started happening when I have added logging using Python standard logging library to my code. I changed my settings.py and views.py. Below you can check what I have changed exactly. Can someone help me keep my logging but avoid the annoying extra output when I run tests? Added to settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'stream': sys.stdout, }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, }, } Added to my views import logging … -
Django Rest Framework + Datatables + Class Based Views + Server Side Processing
How to use Django Rest Framework + Datatables + Class Based Views? -
get_object_or_404 can't find object with primary key
My function in views.py is: def detail(request,pk): singlepost=get_object_or_404(iblog,pk=pk) return render(request,'blog/blogpost.html',{'singlepost':singlepost}) My databse has several items but it return 404 error why ? Also i use path('/',views.detail,name='detail') for mapping url and calling detail function in views.py i test other parts of my project without get_object_or_404 function and every thing go right My problem is in primary key How can i resolve this problem? Thanks -
using mailchimp in django
I am trying to redirect the user to post_list page once they click on subscribe in mail chimp form. But it's not working. Can someone help ? subscribe.html <form action="https://list-manage.com/subscribe/post?xxxxxxxxxx" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate> <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button" onclick="{% url 'post_list' %}"></div> </div> urls.py url(r"^", include("blog.urls")), blog/urls.py url(r'^blog/post_list/$',views.PostListView.as_view(),name='post_list'), views.py class Subscribe(TemplateView): template_name = 'subscribe.html' redirect_field_name = 'blog/post_list.html' -
Django/mod_wsgi looses session when passing to another url
I got stuck with such kind of problem. I'm developing Django application hosted on Apache/mod_wsgi. I replaced the standard Django authentication with REMOTE_USER authentication according to: https://docs.djangoproject.com/en/1.8/howto/auth-remote-user/ I want to get valid user from Apache mod_auth_vas service (which I have ran on server), when user requests: mysite.my/login So, my wsgi.conf is like below and I get prompt for authenticate user on mysite.my/login: WSGIApplicationGroup %{GLOBAL} WSGIPythonHome /proj/tool/appl/portal/.venv WSGIScriptAlias / /proj/tool/appl/portal/portal/wsgi.py WSGIDaemonProcess portal python-path=/proj/tool/appl/portal/.venv/lib/python3.4/site-packages processes=1 threads=60 graceful-timeout=30 maximum-requests=1000 restart-interval=0 header-buffer-size=32768 WSGIProcessGroup portal WSGISocketPrefix /tmp/wsgi LogLevel debug ErrorLog "/proj/weblogs/backendlogs/portal/apache/server1/wsgi/error.log" CustomLog "/proj/weblogs/backendlogs/portal/apache/server1/wsgi/access.log" combined #Timeout 600 <Directory /proj/tool/appl/portal/portal> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> <Location "/login"> Order deny,allow Allow from all AllowOverride AuthConfig Limit FileInfo Indexes AuthType VAS AuthVASUseBasic on AuthName "[ Enter Windows Password ]" Require valid-user </Location> Prompt works okay: How prompt looks like Problem is that: After login on the url: mysite.my/login Django session.user is correct (AuthenticatedUser) and SESSION_KEY is not None value: urls.py from django.conf.urls import url urlpatterns = [ url(r'^index', views.index, name='index') url(r'^login', views.login, name='login'), ] views.py def login(request, node): user = request.user session_key = request.session.session_key return HttpResponse("User is: {}<br />" "SessionKey is: {}<br />" .format(user, session_key)) def index(request, node): user = request.user session_key = request.session.session_key return … -
Django admin: Create UserProfile after User was created
I have a standard UserProfile model which has a OneToOneField field to auth.User model. Every User has to have one and only one UserProfile so I need UserProfile object to be created allways when User is created. The obvious solution is to create a post_save singal: @receiver(post_save,sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.get_or_create(user=instance) But there is a problem. This approach works when user registered themselves or when user was created programatically (eg. via shell). The problem is when user is being created through django-admin. I've added a UserProfile inline into the User admin page which means that there are two forms - for User creation and for UserProfile creation. admin.site.unregister(User) class UserProfileInline(admin.StackedInline): model = MaklerProfile class UserAdmin(BaseUserAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), # (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) # ordering = ('username',) inlines = [UserProfileInline] list_display = ['id', 'username', 'userprofile__display_name','last_login'] Now, when admin is creating a new user via django-admin and fills at least one UserProfile form field, django tries to create a UserProfile for the user two times which returns error. Once it is created because of signal and the second time because there was at least one … -
I can not connect to the container with Elasticsearch
I want add to my project the the Elasticsearch. I'm used the docker-compose. I threw the container port: elasticsearch and can connected from browser, but can not from container: web. I add ELASTICSEARCH_DSL in settings.py, trying to connect via /manage.py shell. But I get error, what doing wrong? settings ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } docker-compose version: '3' services web: restart: always build: ./prod volumes: - ./prod:/usr/app entrypoint: python manage.py runserver ports: - "80:80" links: - elasticsearch elasticsearch: image: elasticsearch ports: - 9200:9200 error requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=9200): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f154e2a5128>: Failed to establish a new connection: [Errno 111] Connection refused',)) -
Django - Form value ERROR [Simple?]
I will provide all the details necessary to this issue. Issue description: When printing or displaying (on the page) the Predmet.predavacIme object I get: <input type="text" name="Ime_Predavaca" value="Elvir" maxlength="50" required id="id_Ime_Predavaca" /> <input type="text" name="Ime_Predavaca" value="Elvir" maxlength="50" required id="id_Ime_Predavaca" /> <input type="text" name="Ime_Predavaca" value="Dzenan" maxlength="50" required id="id_Ime_Predavaca" /> <input type="text" name="Ime_Predavaca" value="Petko" maxlength="50" required id="id_Ime_Predavaca" /> Instead I just wanted a single value of each of these: Desired output: Elvir,Elvir, Dzenan, Petko Modelsmodels.py class ModelRazred(models.Model): godina = models.PositiveSmallIntegerField() brojRazreda = models.PositiveSmallIntegerField() ime = models.CharField(max_length=50) prezime = models.CharField(max_length=50) class Predmet(models.Model): predavacIme = models.CharField(max_length=50) predavacPrezime = models.CharField(max_length=50) imePredmeta = models.CharField(max_length=50) razred = models.ForeignKey(ModelRazred, on_delete=models.CASCADE) URLS urls.py """urlconf for the base application""" from django.urls import path from .views import * urlpatterns = [ #Base path('', home, name='home'), # Stranice path('dodajrazred/', dodajrazred, name='dodajrazred'), path('predmeti/<int:razred_id>/', predmetisubmit, name='predmetisubmit'), path('razred/<int:razred_id>/', detail, name='detail'), path('predmetisubmit/<int:razred_id>/', predmetisubmit, name='predmetisubmit'), # Metode path('predmet_submit/<int:razred_id>/', predmet_submit, name='predmet_submit'), ] VIEWS views.py def detail(request, razred_id): # Funkcija vraca detalje o odredjenom razredu # i njegove ucenike? form = FormPredmet() detaljiRazreda = ModelRazred.objects.get(pk=razred_id) form.razred = detaljiRazreda predmeti = Predmet.objects.filter(razred__id = razred_id) # svi predmeti tog odredjenog razreda data = { 'form': form, 'predmeti':predmeti, 'razred_id': detaljiRazreda.id, 'ime' : detaljiRazreda.ime, 'prezime': detaljiRazreda.prezime } Forms forms.py from django import forms … -
(py1) C:\Users\MOE\Projects\djangoproject>python manage.py migrate
so I tried a tutorial about Django and I got stuck at trying to run manage.py migrate DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangoproject', 'USER': 'root', 'PASSWORD': '123456', 'HOST': 'localhost', 'PORT': '' } (py1) C:\Users\MOE\Projects\djangoproject>python manage.py migrate Traceback (most recent call last): File "C:\Users\MOE\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\MOE\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\MOE\Envs\py1\lib\site-packages\django\db\backends\mysql\base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "C:\Users\MOE\Envs\py1\lib\site-packages\MySQLdb\__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "C:\Users\MOE\Envs\py1\lib\site-packages\MySQLdb\connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") https://www.youtube.com/watch?v=D6esTdOLXh4&t=3261s Thats the tutorial I tried to follow.. but got stuck at 26:30 -
How to get the GET request passed list data?
If I use the params for pass a list in GET method: fetch_physicalserver_list(){ var params = { id_list: this.physicalserver_id_list // there is [24, 26, 27] } this.$Lml_http('get', this.$Api_urls.user_productmanage_physicalserver.list(), params, response => { this.physicalserver_list = response.data.results console.log( response.data.results) }, error => { }) } And in the request, the id_list convert to the id_list[]=24&id_list[]=27&id_list[]=27. and I don't know how to get the id_list in the backend. I use the method to get the id_list[] I will only get the first id, if I get id_list, I will get nothing. the code of get_param_from_query_params method: def get_param_from_query_params(query_params, param): param_temp = None try: mutable = query_params._mutable query_params._mutable = True param_list = query_params.pop(param) param_temp = param_list[0] if (isinstance(param_list, list) and len(param_list) > 0) else '' query_params._mutable = mutable except Exception as e: pass return param_temp So, I have two questions: 1.The params's id_list converted to id_list[]. where is the official description? 2.How can I get the id_list after I passed to the backend? -
Django CreateView get_initial Foreign Key
I have a form and I am trying to use the get_initial method to set a foreign key. The model is class CardioRecord(models.Model): date_uploaded = models.DateField(auto_now=True) client = models.ForeignKey(User, on_delete=models.CASCADE) run_dist = models.FloatField(blank=True, null=True) run_time = models.FloatField(blank=True, null=True) and my view currently is class CardioCreateView(CreateView): model = CardioRecord form_class = CardioRecordForm success_url = 'index' template_name = 'training/cardio_form.html' def get_initial(self): initial = super(CardioCreateView, self).get_initial() client = User.objects.get(id=1) initial.update({'client':client,}) return initial and the error that I am getting is null value in column "client_id" violates not-null constraint which looks like the initial value is not being passed to the form. How do I pass the Foreign Key to the form? -
Retrieve and Display from views.py to template file python Django
How do I retrieve data from the database into views.py and then send it to an HTML file to be displayed? Example: i have a table Average in models.py by using Average.objects.filter(condition) in views.py in a function def avg() i will be able to retrieve the data and store it in a variable how will i proceed from here in sending this data to a html file (student.html) -
DRF send new activation code to registerd user that is not active
this is django rest framework project . this time i want to resend account activation code to registered user(that is not active at the moment) i wrote view like this but i get server response that say: user account is disabled ... i know user is disabled right now but i want to send new activation code to him according his/her email and id.. this is my view: any suggestion for me to solve this issue? class ResendActivationCode(APIView): permission_classes = [AllowAny] activation_code = code_generator() def get(self, request): print(request.user) capname = str('re' + request.user.id) iscached = cache.get(capname) if not iscached: cache.set(capname, 1, 120) email = request.user.email Profile.objects.filter(user_id=request.user.id).update(**{'activation_key': self.activation_code}) subject = "complete you registration" message = "Thankyou. please enter this code to done your registration progress {}".format(self.activation_code) html_message = "http://localhost:4200/accounts/activation/{}".format(self.activation_code) froms = "mail@gmail.com" # html_template = render_to_string('mail/reg_mail.html', {}) send_mail( subject, message, froms, [email], html_message=html_message, # fail_silently=False, ) return Response("ok") else: return Response("time limit") and this is related model: (this is profile model that have relation to User table and have activation_code field to store code) class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='profile') activation_key = models.CharField(max_length=200) bio = models.CharField(max_length=250, null=True, blank=True) email = models.EmailField(null=True, blank=True) job = models.CharField(default="",max_length=250, null=True) server response: detail":"User account … -
Make user login with dialog boxes (Bootstrap Modals)
I am using django builtin auth_views for user authentication, but sometimes user need to authenticate with a modal and for that I am using bootstrap modals but it is not rendering form to that modal. Here is my modal: {% load widget_tweaks %} <div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Login Required</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="post" action="{% url 'accounts:seller_login' %}"> {% csrf_token %} {% render_field form.username|add_class:"form-control" %} {% render_field form.password|add_class:"form-control" %} <input type="hidden" name="next" value="{{ request.path }}"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <input class="btn btn-primary" type="submit" name="" value="Login"> </form> </div> </div> Here is my url.py url(r'^login/$', auth_views.LoginView.as_view(template_name= 'accounts/registered/login.html', redirect_field_name='next',), name='login'), In this I need to render the form and if any errors it should render to that modal only. I had searched how to render forms to other templates but nothing found useful! -
Django: TemplateView or FormView?
I am currently trying to bring my function-based view into a class-based view. The question I am currently struggling with is if I should either trying to move it into a TemplateView with FormMixin or in a FormView with ContentMixin. Do you have any tips on how to decide what's best? def event_detail_view(request, event, organizer): queryset = Event.objects.filter(organizer__slug=organizer) event = get_object_or_404(queryset, slug=event) tickets = collect_all_tickets(event, organizer) ReserveFormSet = formset_factory(ReserveForm, formset=BaseReserveFormSet, extra=0) formset = ReserveFormSet( initial=tickets, # Example [{'ticket': "Early Bird"}, {'ticket': "Regular Ticket"},] form_kwargs={'organizer_slug': organizer} ) if request.method == 'POST': formset = ReserveFormSet( request.POST, initial=tickets, form_kwargs={'organizer_slug': organizer} ) if formset.is_valid(): order_reference = unique_order_reference_generator() for form in formset: ticket_name = form.cleaned_data['ticket'].name int_or_empty = form.cleaned_data['quantity'] qty = is_int_or_zero(int_or_empty) if qty > 0: obj = form.save(commit=False) obj.ticket_name = ticket_name obj.order_reference = order_reference obj.save() return redirect('organizers:index', organizer=organizer) ticket_status = {} ticket_status['sold_out'] = TicketStatus.SOLD_OUT ticket_status['on_sale'] = TicketStatus.ON_SALE return render(request, 'events/event_detail.html', { 'event': event, 'formset': formset, 'ticket_status': ticket_status, 'tickets': tickets }) -
Using an inline formset in generic update view for editing related objects via a foreign key
It's clear from the django docs how to use an inline formset in a view. But what if, following an example in the docs, you'd like to edit books related to an author via an Authors generic update view. Is there a better or alternative approach to the following: Create additional formset and add it to a context in get_context_data() method of a generic update view. Deal with this additional formset in a form_valid() method of a generic update view - check if it's valid and save or update the context and return back if it's not. models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) views.py class AuthorUpdate(UpdateView): model = Author fields = '__all__' def get_context_data(self, **kwargs): data = super(AuthorUpdate, self).get_context_data(**kwargs) BooksFormSet = inlineformset_factory(Author, Book, fields='__all__', extra=1) if self.request.POST: # Create a formset instance to edit an existing model object, # but use POST data to populate the formset. data['books'] = BooksFormSet(self.request.POST, instance=self.get_object()) else: # Create a formset with the data from model object and add it to context data['books'] = BooksFormSet(instance=self.get_object()) return data def form_valid(self, form): context = self.get_context_data() books = context['books'] with transaction.atomic(): self.object = form.save() if … -
IDE for Django Template Intellisense/Autocomplete
I am looking for examples of IDEs that provide intellisense/autocomplete for the context variables in the view template files for Django. I found that Visual Studio does it where you get your context variables in the template. It seems like that is only available for Windows though. What are some other options for context intellisense/autocomplete? I have tried PyCharm Professional and VS Code to no avail. Basically, I am looking to get a near C# Razor experience with the template model or at least the closest I can for a dynamic language. -
Django URL Does not Exist?
This is very strange, any ideas?: Here is my code for urls.py from django.contrib import admin from django.conf.urls import include from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('videos/', include('videos.urls')) ] And videos/urls.py: from django.urls import path from . import views urlpatterns = [ path(r'^$', views.index, name='index'), ] -
How can I filter the physicalserver if its id is in the given param?
How can I filter the physicalserver if its id is in the given param? class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [IsSuperAdminOrObjEqualsSelf] pagination_class = CommonPagination def get_queryset(self): query_params = self.request.query_params qs = PhysicalServer.objects.filter(user=self.request.user) id_list = get_param_from_query_params(query_params, 'id_list') if id_list: qs = qs.filter(Q(id__in=id_list)) # I want to filter if the physicalserver id is in the `id_list` return qs the code of the method: def get_param_from_query_params(query_params, param): """ :param query_params: :param param: :return: """ param_temp = None try: mutable = query_params._mutable query_params._mutable = True param_list = query_params.pop(param) param_temp = param_list[0] if (isinstance(param_list, list) and len(param_list) > 0) else '' query_params._mutable = mutable except Exception as e: pass return param_temp How can I filter the physicalserver if its id is in the given param?