Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python - django autentication - anonymous user after login
I have a django server which acts as an API (i.e. listens to requests and returns data ONLY), and I want this API to be accessible only to authenticated users. I read about the django authentication system, and tried to implement it according to the documentation (https://docs.djangoproject.com/en/2.0/topics/auth/default/). I wrote a small web-page just to test the authentication - login was successful (server was able to authenticate and login the user), but when attempting to reach a restricted view I have no access, and the request.user received is an AnonymousUser instead of the logged in user. I am using Python 3.6.5 and Django 2.0.4 Server code: @csrf_exempt def dologin(request): username = request.POST.get('username') password = request.POST.get('password') if not username or not password: return HttpResponse('missing username or password', status=400) user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponse(user) else: return HttpResponse('bad credentials', status=422) def dologout(request): logout(request) return HttpResponse('success') @login_required() def testAccess(request): return HttpResponse('ok') def checkUser(request): u = "anonymous" if not request.user.is_authenticated else request.user.username return HttpResponse(u) Client code: <label>username:</label> <input type="text" id="uin"/> <label>username:</label> <input type="text" id="pin"/> <button id="inbtn">login</button> <button id="outbtn">logout</button> <button id="test">test access</button> <button id="check">check user</button> <div id="res"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script> <script> $("#inbtn").click(function(){ u = $("#uin").val(); p = $("#pin").val(); … -
related name in parent model in django if inherited in other model
I created a model which can be inherited in other models Parent Model class Edit_Lane_Info(models.Model): lane_info = models.OneToOneField(Edit_Lane, related_name="$(class)s", on_delete=models.CASCADE) def delete(self, *args, **kwargs): super().delete(*args, **kwargs) if self.lane_info: self.lane_info.delete() class Meta: abstract = True class Status (Edit_Lane_Info, models.Model): # parent class inherited ...... class Anpr(Edit_Lane_Info, models.Model): # parent class inherited .... class Sensor_Details(Edit_Lane_Info, models.Model): # parent class inherited ............. Now my question is how can I pass related_name in Edit_Lane_Info(parent model) uniquely -
Django backend with a javascript frontend - best practices
I stumbled upon google's material design web components ("https://material.io/") and would like to implement it in my projects. The only problem is that I've never used a javascript frontend before. Note: Google's Material Design is the successor of Material Design Lite. I received a recommendation to learn angular and implement Google's material design components through angular and have my frontend (angular) communicate with my backend (django) through an API. 1- Is this really the best way to proceed if only the web components are needed? Can we not just import the CSS and JS like we did with bootstrap and use Django/jinja to render views? 2- It seems like node.js / NPM is required to use angular and Google's material design, however, is that just during development? Or will we face complications when trying to deploy a django backend and javascript front end? -
Django Celery periodic task example
I need a minimum example to do periodic task (run some function after every 5 minutes, or run something at 12:00:00 etc.). In my myapp/tasks.py, I have, from celery.task.schedules import crontab from celery.decorators import periodic_task from celery import task @periodic_task(run_every=(crontab(hour="*", minute=1)), name="run_every_1_minutes", ignore_result=True) def return_5(): return 5 @task def test(): return "test" When I run celery workers it does show the tasks (given below) but does not return any values (in either terminal or flower). [tasks] . mathematica.core.tasks.test . run_every_1_minutes Please provide a minimum example or hints to achieve the desired results. Background: I have a config/celery.py which contains the following: import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() And in my config/__init__.py, I have from .celery import app as celery_app __all__ = ['celery_app'] I added a function something like below in myapp/tasks.py from celery import task @task def test(): return "test" When I run test.delay() from shell, it runs successfully and also shows the task information in flower -
Overlay a toolbar over Cesium Viewer/Map
Hi I am trying to overlay a toolbar on the Cesium Viewer/Map but whenever I try to do the div class = toolbar like in the sandcastle example, the buttons or anything I add always shows up under the map. I want something like this: http://i.imgur.com/KKI2W5R.png Here's what I have so far: Index.html <html> <head> <title>Demo</title> </head> <body> {% load staticfiles%} <script src= {% static "js/Cesium.js" %} type="text/javascript"></script> <div id="cesiumContainer"></div> <div class="toolbar-left"> <button onclick="alert('You clicked!');">Click me!</button> </div> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'test/hello.css' %}" /> <script> var viewer = new Cesium.Viewer('cesiumContainer'); </script> </body> </html> -
Problems with Django REST framework filtering?
I have this problem while using the Django Rest Framework. I am trying to do a get request using patient id. Now, lets say I look for patientid=6, the api returns results with patientid=6 ,patientid=26 and any ids that contain the number '6'. It looks like it searches for a substring.I want to make it work such that patient id=6 returns only the patientid results with id =6 serializers.py class Radiologypdfserializerdata(serializers.ModelSerializer): class Meta: model = models.Radiologypdf fields = ( 'patientid', 'testinfo', 'clinicalindication', 'attendingdoctor', 'patientname', 'age', 'mobilenumber', 'sex', 'email', 'doctorsname', 'doctorsregistrationnumber', 'clinicname', 'doctorstelno', 'createdtime', 'radiology_id', 'created', ) api.py class RadiologypdfViewSet(viewsets.ModelViewSet): """ViewSet for the radiology class""" queryset = models.Radiologypdf.objects.all() serializer_class = serializers.Radiologypdfserializerdata permission_classes = [permissions.IsAuthenticated] filter_backends = (filters.SearchFilter,) search_fields = ('patientid','radiology_id') -
How to display a field from a modelchoice
I have a class in my forms and a object called tiposervico (ForeignKey). See bellow. In my template, after select a tiposervico I would like to display 'descricao' field on my screen. How can i do that? class servicoForm(forms.ModelForm): tiposervico = forms.ModelChoiceField(queryset=tiposervico.objects.all(), required=True) tiposervico -> id, descricao -
Getting and inserting the value of a CSRF cookie set by Django in Angular
I'm having some trouble getting the CSRF integration between Django and Angular to work. I made an earlier broader post about that here.. The problem is that logged in users can't make post-requests from the front-end, but they can make the exact same requests from Django's browsable API through forms. I'm setting a {% csrf_token %} at the index template that Django serves and I am using Angular's built it XSRFS strategy to set attack a header to http requests, but I think the problem is that I'm not catching the value provided by Django's generated csrf token and can't figure out how to implement gathering that data and attaching it to my Angular http-request cookies. Here's the code for the module that provides the strategy: import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/http' import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { RegisterComponent } from './register/register.component'; import { LoginComponent } from './login/login.component'; import { AlertComponent } from './_directives/alert.component'; import { ProfileComponent } from './profile/profile.component'; import { AuthGuardService } from … -
How to access run-time request.session values in forms.py definition?
I have an inventory management app that will be serving multiple locations (called contexts in my app). When a user is logged in, their current context is stored as a value in request.sessions. I would like users to only be able to browse and retrieve records for their own location. I've been trying to this by filtering the queryset that is called in the form definition to populate the select dropdown, i.e. referenced_catalog = forms.ModelChoiceField( queryset=Inventory_unit_catalog.objects.all().filter(parent_business_unit_context_id=user_context_id), I've tried implementing several different (but similar) approaches from various SO posts, that involve defining an init block to the form, such as: def __init__(self, *args, **kwargs): self.user_context_id = kwargs.pop('user_context_id', None) super(InventoryStockAddForm, self).__init__(*args, **kwargs) But the queryset definition still returns that user_context_id is undefined, whether as written or as self.user_context_id (different SO answers had one way or the other). I've even tried using the SessionStore per https://djangobook.com/using-sessions-views-2/: SessionStore = import_module(settings.SESSION_ENGINE).SessionStore s = SessionStore() user_context_id = s['user_context_id'] but it always fails at the moment the forms.py is updated as Django validates the code and cannot find a key value at the moment of validation. Any advice would be appreciated, thanks! -
empty POST results of an LI
I have the following form using the POST method. <form action = "{% url 'submittedupdate' %}" form method = "POST"> {% csrf_token %} <div class="well"> <h4 style="margin-top: 0"><strong>Update Application(s)</strong></h4> {% for app in applicationaccess %} <li name = "report_id" value = "{{app.report_id}}">{{ app.report_name_sc }}</li> {% endfor %} </div> </form> The current form displays the data correctly, but when I try to retrieve the request in the next view with currlist = request.POST.getlist('report_id') print(currlist) I get an empty list. In the previous view applicationaccess is defined as reportaccess shown below: owner = ADMirror.objects.get (employeentname=request.POST.get('userpost')) currentaccess = QVReportAccess.objects.filter(ntname = 'owner.employeentname, active = 1).values_list('sr_datareduce_summary_code', flat = True).distinct() reportIds = QVReportAccess.objects.filter(ntname = 'owner.employeentname).values_list('report_id', flat=True) currentcheckedlist = request.POST.getlist('current_report') reportaccess = QvReportList.objects.filter(report_id__in= currentcheckedlist).values('report_id','report_name_sc').distinct() Why am I getting an empty list and how can I get the values from report_id in the for loop above? -
Django database relationship - TypeError: 'ManyToOneRel' object is not iterable
I am 3 days trying to make the relationship One to Many with the database using the table "Alternativas" through the resposta of the table "Questoes". I want to make a quiz system, where the questions are stored in a table in the DB, and the answers is in another table and in this way make a relationship between them, but it return's the following error when trying to pull the response column, follow's the print. TypeError: 'ManyToOneRel' object is not iterable models.py: class Questoes(models.Model): id = models.IntegerField(max_length=10, primary_key=True) enunciado = models.CharField(max_length=255, null=False) alternativa_correta = models.CharField(max_length=255, null=True) resposta = models.ManyToOneRel('resposta', to='Alternativas', field_name='descricao') class Alternativas(models.Model): id = models.IntegerField(max_length=10, primary_key=True) questao_id = models.ForeignKey('Questoes', on_delete=CASCADE, db_column="questao_id") descricao = models.CharField(max_length=255, null=True) Views.py: def dashboard(request): if request.method == 'POST': questoes = {} questoes['questoes'] = Questoes.objects.values('id') print('=======================================================================') print(questoes) print('=======================================================================') for a in Questoes.resposta: print(a.descricao) print('======================================================================') Thanks for the support. -
Display the descriptive status of options
I define a article_table model data in modles.py, especially set a options attribute for status class Article(models.Model): STATUS = ( (0, 'normal'), (-1, 'deleted'), ) block = models.ForeignKey(Block, on_delete=models.CASCADE) title = models.CharField(max_length=100) author = models.CharField(max_length=100) content = models.CharField(max_length=1000) # set the widget status = models.IntegerField(choices=STATUS) date_created = models.DateTimeField(default=datetime.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title When I check the responded html, it display status with 0 from database rather than its description 'normal' The status did not show normal as I intended. The template of article_list.html <table class="table table-bordered"> <tr> <th>Status</th> <th>Title</th> <th>Author</th> <th>Latest Updated</th> </tr> {% for article in articles %} <tr> <td>{{ article.status }}</td> <td>{{ article.title }}</td> <td>{{ article.author }}</td> <td>{{ article.date_updated }}</td> </tr> {% endfor %} </table> How to solve such a problem? -
range mask error GenericIPAddressField()
using django how can I set mask range if I use models.GenericIPAddressField() without generating example error 127.0.0.0.1/24 -
Django project as desktop app
My Django Project contains a web tool which i would like to deploy as a desktop app. I googled a it and every content is quite old and/or badly documented. I never tried to make an desktop app before so i have no idea on how to do this and even less of an idea how a virtual environment can added to run the test server. It would be great if you could give me a how-to or a tutorial for beginners. Thanks a lot! -
JQuery tokenfield with django not working
I am trying to incorporate a search field in a django registration form. I would like to use a bootstrap tokenfield that searches a django model for possible matches to the search string. I've been struggling with this for a couple of days now. Here is my code below. <div class="form-inline" id="keywords_div"> {% csrf_token %} <input type="text" name="search_text" class="form-control" id="tokenfield" placeholder="Enter keyword" style="width: 50%" /> <button type="button" id="addKeyword-btn" class="btn btn-primary">Add</button> My JQuery code. $(function(){ //auto complete ajax code. $('#tokenfield').tokenfield({ autocomplete: { //source:['red','blue','green','yellow','violet','brown','purple','black','white'], delay: 100 }, showAutocompleteOnFocus: true, }).keyup(function(){ alert('key pressed'); $.ajax({ url: "/user_account/auto_complete_search/", type: 'POST', data: { 'search_text': $('#tokenfield').val(), 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val() }, success: function(data){ console.log(data) }, dataType: 'text' }); }); }); }); Django View #This is the function that handle the auto complete search functionality. def autocomplete_search_view(request): if request.method == 'POST': search_text = request.POST['search_text'] else: search_text = '' keywords = Keywords.objects.filter(keyword__icontains=search_text) #data = serializers.serialize('json', keywords, fields=('keyword')) return HttpResponse('Query completed', content_type='application/text') user_account/urls.py url(r'^auto_complete_search/$', autocomplete_search_view, name='autocomplete_search'), The error from the browser. What am I doing wrong here? -
Serializer failing to add extra data
In django rest framework i am trying to add an object in a ModelSerializer with some custom functionality. I want one of the fields to be set to self.request.user and i have the following view: class GigSubmitView(generics.CreateAPIView): permission_classes = (ProviderRW,) serializer_class = serializers.GigSubmitSerializer queryset = models.Gig.objects def perform_create(self, serializer): serializer.save(provider=self.request.user) However that doesn't seem to be the correct answer. What should i do instead? -
Why should I set max_length when using Choices in a Django model?
In the official Django 2 tutorial I found this: from django.db import models class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) Now my question is does using choices mean that only either of the four defined values is valid for this field? If so what is the use of specifying the max_length? If not, why not use a validator that validates if the value is actually exacly one of the specified ones or at least a validator that only accepts an specific length not just an upper bound. -
How to create preview image of pdf file using reportlab
I have generated a pdf file using reportlab.lib, in python django framework. I need to create a preview image of that pdf to show in my page. How can I create a preview image of pdf file using reportlab, python library -
Django 403 forbidden when sending Post-requests from Angular only when user is logged on
I've created a back-end Django application and am currently working on hooking up an Angular front-end that requests data from API's set up using Django rest framework and have run into the problem that my logged in users (in the back-end, them being logged in on the front-end doesn't matter) get 403 on all post-requests to the API. Which I figure is because of the CSRF protection in Django. I have look at a thread that tackled this exact problem for this and have attempted to implement the solution from this thread with no luck. Logged out users can send post-requests to register or log in just fine. But when a logged in user tries to it gets a 403. Sending the same data while browsing the DRF API is successful, which is why I think it's related to CSRF. To be a little more clear, if I'm logged in as a user on the front-end and try to log-in or register a new user (those parts aren't blocked off in development) I get a 403 response. If I'm logged in on the browsable API and send the exact same post-content it works with successfully attempting to log me in … -
celery dont run all the code
It is part of my code. try: for li in lists[count+9:]: if not li in url_index: time.sleep(0.5) if len(url_index)<15: url_index.append(li) else: url_index.pop(0) url_index.append(li) req=requests.get(li) # d=download.objects.create(name=bookget[0],book_list=li) # d.save() selector=scrapy.Selector(text=req.content.decode('gbk','ignore')) chapter_name=selector.xpath('//h1/text()').extract_first() chapter_content=selector.xpath('//div[@id="content"]').xpath('string(.)').extract_first() with open(basedir+'index/'+str(count)+'.txt','w')as f: f.write(chapter_name+'\n') if chapter_content is None: chapter_content='' f.write(chapter_content) count+=1 print(count) print('if') print('for') except Exception as e: print('for') as we can see in the following picture,the 'print(count)' was run but print(if) and print('for') did not run. Who can tell me why. this is the picture -
ManyToManyRelationship in a django model
let's suppose a city have multiple company. city1:{ company1: [phone1, email1] company2: [phone1, email2, phone3] } each company can have one or more phone, email. I wanted to store company info as < city1, company1:[phone1, email1] > < city1, company2:[phone1, email2, phone3] > I tried as.. class City(models.Model): name = models.CharField(max_length=200, blank=True, null=True) class CompanyDetails(models.Model): com_name = models.ForeignKey(City) email = models.EmailField(max_length=100, blank=True, null=True) mobile_number = models.CharField(max_length=10, blank=True, null=True) Because a company can have multiple phone or email, So how to define this. any suggestions. -
Fetching rows from a table in django
views.py: rows = None locname = "select location_name from locations" cursor=con.cursor() a=cursor.execute(locname) rows=a.fetchall() return render(request,'project/output.html',{'rows':rows}) output.py: <html> <body> {{rows}} </body> </html> When I try to print rows value in output.html,its printing None instead of the value present in rows.Please suggest what is wrong with my code -
How can I create a ManyToMany relationship with the same model in Django and save to database?
I have a form which is collecting data about a variable to be created. I want to create a list of variables which are already there in the database. I am doing this by creating a ManyToMany relationship. When I start the server, the list of variables gets saved on the application, but it does not alter the database field named selectiveList. forms.py class VariableForm(ModelForm): class Meta: model = variable fields = ['name', 'area', 'parameterName', 'order', 'type', 'format', 'units', 'comboItems', 'hiAlarm', 'loAlarm', 'scaleHiMax', 'scaleLoMax', 'deviationAlarm','selectiveList', 'round', 'days', 'required', 'hidden', 'readOnly', 'holdLast', 'calibrationFrequency', 'dateNextCalibration', 'triggerCalibrated'] widgets = { 'comboItems': forms.Textarea(attrs={'rows':1, 'cols': 40, 'style': 'height: 2em;padding-top:0'}), 'forceValue': forms.Textarea(attrs={'rows':1, 'cols': 40, 'style': 'height: 2em;padding-top:0', 'placeholder':'This will force all input to this variable'}) } #selectiveList = forms.ModelMultipleChoiceField(queryset=variable.objects.all().order_by('-name').reverse()) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(VariableForm, self).__init__(*args, **kwargs) self.fields['round'] = forms.ModelMultipleChoiceField( queryset=opRound.objects.all(), widget=forms.SelectMultiple, label='Rounds', required=False ) self.fields['selectiveList'] = forms.ModelMultipleChoiceField( queryset=variable.objects.all().order_by('-name').reverse(), widget=forms.SelectMultiple, label='Select Variables', required=False ) self.fields['days'] = forms.ModelMultipleChoiceField( queryset=dayOfWeek.objects.all(), widget=forms.SelectMultiple, label='Days', required=False ) self.fields['area'].choices = AreaIterator(request = self.request) try: self.fields['order'].initial = variable.objects.latest().order+1 except Exception,e: print e model.py class variable(models.Model): name = models.CharField(max_length=255) area = models.ForeignKey(area)#parent order = models.IntegerField("Order Index (0 is first, 1 is next, etc.)",default=999)#order index to display in order correctly, ascending type … -
RadioSelect() with queryset in django
In my forms.py i have this field bellow that return only 2 records, but display 3 records in my screen. I don´t want the first one "---------". tipopagamento = forms.ModelChoiceField(widget=forms.RadioSelect(), queryset=tipopagamento.objects.all(), required=True) My screen display: -
Django form: Check for unique name
In my form I want to check if the descriptor name is unique for this project. Models.py class Descriptor (models.Model): project = models.ForeignKey('Project', on_delete=models.CASCADE, default='1') name = models.CharField(max_length=1000) forms.py class DescriptorForm(forms.ModelForm): class Meta: model = Descriptor fields = ('name','project') widgets = {'project': forms.HiddenInput()} def clean_name(self): name = self.cleaned_data['name'] project = self.fields['project'] if Descriptor.objects.filter(project=project, name__iexact=name).exists(): raise ValidationError("Descriptor with this name already exists") return name I am getting TypeError: int() argument must be a string, a bytes-like object or a number, not 'ModelChoiceField' Without project = self.fields['project'] and project=project thec check works, but for all Descriptors and not just the ones connected to this Project. What do i have to change to make this work?