Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF token issue using dynamic login
I have have been looking in previous answers on Stack but nothing seems to apply to my app issue I am getting a CSRF issue Forbidden (CSRF token missing or incorrect.): /registration/auth_HRlogin/ It worked perfect until I modified my views.py in order to reverse to different page in function of the kind of user that login .. if he is HR or Employee or Candidate def HR_login(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = MyUser.objects.filter(email=email) if user: user=user[0] if user.is_active & user.is_hr & user.check_password(password): login(request,user) return HttpResponseRedirect(reverse('website:hr_index')) elif user.is_active & user.is_employee & user.check_password(password): login(request,user) return HttpResponseRedirect(reverse('website:employee_index')) elif user.is_active & user.is_candidate & user.check_password(password): login(request,user) return HttpResponseRedirect(reverse('website:candidate_index')) else: HttpResponse("Account not active, please contact Admin") else: print("Someone tried to login and failed") return HttpResponse("Invalid login detailed supplied!") else: return render(request,'HR_login.html',{}) No need to mention that I do have the CSRF token in my form and in my setting.py ;) Any Idea ? -
I am new to django and want to use a google api? How should I proceed?
I want to use the google classroom api but I am facing difficulty in getting started... any suggestions? -
Pick up multiple variables with get_context_data Django
I have a question about CBV Django process and get_context_data(). I would like to get some different variables and I don't overcome to do it with my function. This is the function : class IdentitySocietePDFCreatingView(LoginRequiredMixin, TemplateView) : template_name = 'Identity_Societe_PDF.html' model = Societe def get_context_data(self, **kwargs) : SID = Logger.login(lib.Global_variables.GED_LOG_USER, lib.Global_variables.GED_LOG_MDP) context_data = super(IdentitySocietePDFCreatingView, self).get_context_data(**kwargs) id = self.kwargs['id'] societe = get_object_or_404(Societe, pk=id) obj = Societe.objects.filter (Nom=societe.Nom, SIRET=societe.SIRET, SIREN=societe.SIREN, Ville=societe.Ville) if obj: sc_obj = obj[0] ''' Rest of my script '''' ''' I have a variable named folderID which must be in my template '''' context_data['queryset'] = obj return context_data My question is : How I can add folderID variable inside context_data ? I have to display in my template obj and folderID but I don't overcome to add both variable in context_data. -
How to check if the value of a field has been deleted in Python/ Django
i'm trying to check if a value of field has been deleted and then return False or return true if all the fields contain values. My code actually doesn't check the value in the fields but just check if the fields exists, how to heck the values of every specific fields? This is my models and in my views i have to check the function. class CompanyDirector(models.Model): username = models.CharField(max_length=128, blank=True, null=True) directorTitle = models.CharField(max_length=8, blank=True, null=True) directorName = models.CharField(max_length=64, blank=True, null=True) directorSurname = models.CharField(max_length=64, blank=True, null=True) directorId = models.CharField(max_length=16, blank=True, null=True) proffessionStartDate = models.DateTimeField(blank=True, null=True) ret = {'complete': False} try: company_director = CompanyDirector.objects.filter(company__token=token).first() if company_director: ret['complete'] = True for field in company_director._meta.get_all_field_names(): if not getattr(company_director, field): ret['complete'] = False break; except ValueError as e: print (e) return Response(ret) -
Django serialization: AttributeError when attempting to get a value for field on serializer
I am getting the following error, AttributeError: Got AttributeError when attempting to get a value for field devicedetails on serializer DISerializer. The serializer field might be named incorrectly and not match any attribute or key on the Device instance. Original exception text was: 'Device' object has no attribute 'devicedetails'. My models.py :- class DeviceInfo(models.Model): vendor = models.CharField(max_length=250) device_type = models.CharField(max_length=250) modelname = models.CharField(max_length=100) class Device(models.Model): name = models.CharField(max_length=100, primary_key=True) username = models.TextField() password = EncryptedTextField() deviceinfo = models.ForeignKey(DeviceInfo, null=True) class DeviceDetails(models.Model): device = models.ForeignKey(Device) serial_number = models.CharField(max_length=100) version = models.CharField(max_length=100) serializer.py :- class DeviceInfoSerializer(serializers.ModelSerializer): class Meta: model = DeviceInfo fields = ("id", "vendor", "device_type", "modelname") class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ("name","username", "password", "deviceinfo") class DeviceDetailsSerializer(serializers.ModelSerializer): class Meta: model = DevieceDetails fields = ("device", "serial_number", "version") class DISerializer(serializers.ModelSerializer): deviceinfo = DeviceInfoSerializer(read_only=True) devicedetails = DeviceDetailsSerializer(many=True) class Meta: model = Device fields = ("name", "username", "password", "deviceinfo", "devicedetails") views.py :- def list(self, request): list = Device.objects.all() serializer = DISerializer(list, many=True) -
Checksums are calculated after the form validation: how to notify the users of an error
Django 1.11.6 I'm developing a document archive. So, I calculate checksums to control that documents are still present, that they are not corrupt etc. Another side of this is that I can control whether a file has already been uploaded. It is important: no need to duplicate the files. I upload files through Django admin. There is a form prepared. But the problem is: form validators seems to be not very useful here. At least I can't invent how to use a form validator here. But post_save signal are useful: here we have a file already uploaded. We calculate the checksum of the file (using md5). But if unique=True for the checksum, IntegrityError is risen. It is Ok and predictable. But could you help me understand how to notify the user about this? Any method would suffice. It is just for our staff: no need to organize a brilliant html layout. But what is important is to show that the uploaded file coincides with an existing file with the following id. Could you help me with this? models.py class FileChecksum(models.Model): checksum = models.CharField(blank=True, null=False, unique=True, max_length=255, verbose_name=_("checksum")) def __str__(self): return self.checksum class Image(models.Model): file = models.ImageField(blank=False, verbose_name=_("Image"), max_length=255, upload_to=get_sheet_path) file_checksum … -
Loading fixtures in both public and test schemas with Django-tenant-schemas
I am trying to move tests written for a single tenant approach to a multi tenant approach (Django + Django REST Framework + django-tenant-schemas). I am wondering how the fixtures are handled using the FastTenantTestCase and rest_framework.test.APITestCase (inheriting from django TestCase). Indeed, it is loading all the fixtures in the public schema of the test DB but nothing is loaded in the test schema, thus leading all the tests to fail because nothing is present in the database. Did I miss something in the documentation or is it a missing feature ? Does anyone manage -
Django: Queries and calculations inside CreateView
I am relatively new to Django, so I am not sure is what I am asking possible to do. I am building a website with funcionality to rate users and write reviews about them. I have model for users (that has average rating field) and model for reviews (with fields of author, user_profile, grade and review. I am using CreateView for making reviews. I am trying to do the following: To make query to get all previous grades of that person (from Reviews model). Make calculations (sum all previous grades, add the new one and all that divide by number of grades(including new grade) Save new average grade to UserProfile model Save review to Review model Redirect user to current detail view Models.py class UserProfile(models.Model): ... avg_grade = models.FloatField(blank=True, null=True) ... class Reviews(models.Model): user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) grade = models.PositiveIntegerField() review = models.CharField(max_length=256, null=True, blank=True) author = models.CharField(max_length=256) In views.py I managed to make query of grades of that user, but not sure where to do calculations for new average grade(if this is possible inside Class-Based-View): class CreateReview(LoginRequiredMixin, CreateView): form_class = Forma_recenzije success_url = reverse_lazy('detail') template_name = 'accounts/recenzija.html' def get_queryset(self): u = UserProfile.objects.get(id=int(self.kwargs['pk'])) return Reviews.objects.filter(user_profile=u) def form_valid(self, form): form.instance.author = … -
Django Allauth different login redirection for facebook and twitter python 2.7
I am trying to redirect the different pages for the Facebook and Twitter in Django 1.11.5 using the Django-Allauth. I have tried something like this but it didn't work in my case: import allauth.socialaccount.providers as ASP if ASP == 'facebook': LOGIN_REDIRECT_URL = '/test/' else: LOGIN_REDIRECT_URL = '/' I want to know how I can redirect the url for different social media on different links? Kindly suggested me the improvements in the code. -
Clustering two queries from Neo4j python, creating a json for Alchemy.js to visualize the data
I have two querysets nodes_query, edges_query set how to cluster them and create a json so that alchemy.js can be used for data visualisation? Dependencies Mac Osx, python 3.4.3, django 1.9, neo4j-driver Default datasets provided by NEO4j movie dataset, person dataset. **My Views.py** def my_own(request): driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "password")) session = driver.session() # match (n) optional match (n)-[r]-() return n,r: nodes_query = session.run("MATCH (a:Person)-[:ACTED_IN]->(:Movie)RETURN DISTINCT ID(a) AS id, a.name AS name") edges_query = session.run("MATCH (a1:Person)-[:ACTED_IN]->(:Movie)<-[:ACTED_IN]-(a2:Person)RETURN ID(a1) AS source, ID(a2) AS target") result = session.run("MATCH (n) OPTIONAL MATCH (n)-[r]-() RETURN n,r") session.close() return render(request, "friends.html") -
DjangoCMS: disable login via http, force https
Our DjangoCMS site is accessible via http and https. Anonymous usage via http is ok. But I want to disable logins via http. Is there a way to force the usage of https as soon as the user wants to login? Even the login-page (with username and password fields) should not be available via http. Background: I don't want the password to go over the wire unencrypted. -
How to set variables to supervisor and gunicorn config from os variables?
Hi i have set up some variables to Linux(have added them to ~/.bashrc). I know that it is possible to set variables to supervisor environment= KEY=value and to gunicorn i may simple add in config export KEY1='value' Is any way to add variables only to ~/.bashrc and take them to all configs? Thx for any help. -
Django object not iterable, why?
I want display username if he click on i want join button using ajax. I have html that look like this : <div class="who_come"> <form class="form-inline" role="form" method="post" id="joinToEventForm"> {% csrf_token %} <p align="left"><b ><button type="submit">I want join</button></b></p></b></p> </form> {% for u in who_come %} <p><a href="profile/{{u.visiter}}">{{u.visiter}}</a></p> {% endfor %} </div> i use this code to produce my ajax : $('#joinToEventForm').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check $.ajax({ type:'POST', data:{ csrfmiddlewaretoken:'{{ csrf_token }}' }, success : function () { alert("You are on Envent") } }); }); it code works, and write to database what i need, but it return to me 500 error code with TypeError: 'WhoComeOnEvent' object is not iterable. I can't understand what is a problem it is my model: class WhoComeOnEvent(models.Model): visiter = models.ForeignKey(User, related_name='WhoComeOnEvent') which_event = models.ForeignKey(Topic, related_name='WhoComeOnEvent') def __str__(self): return '%s go to %s' % (self.visiter.username, self.which_event.subject) it is my view : def p(request, pk): user = request.user topic = get_object_or_404(Topic, pk=pk) post = get_object_or_404(Post, pk=pk) comment = Comments.objects.filter(pk=pk) who_come = WhoComeOnEvent.objects.filter(pk=pk) if request.is_ajax(): who_come = WhoComeOnEvent.objects.create( visiter=user, which_event=post.topic ) if request.method == 'POST': form = CustomCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.creator = user comment.save() comment = Comments.objects.create( body=form.cleaned_data.get('body'), creator=user, … -
Django-Allauth how to check if the user is authenticated with twitter or facebook python2.7
I have created an application through which I can authorize user with Facebook or twitter. Here is the code: {% if user.is_authenticated %} <a href="/accounts/logout/" title="Log out from the website"> <button type="button" class="fb__submit"> <i class="fa fa-facebook" style="font-size: 250%" aria-hidden="true"></i> Log out </button> </a> <!--<a href="/accounts/logout/"><div>Sign Out</div></a>--> {% else %} <a href="{% provider_login_url "facebook" %}" title="Login with Facebook"> <button type="button" class="fb__submit btn-space">Login in with <i class="fa fa-facebook" style="font-size: 250%" aria-hidden="true"> </i> </button> </a> <!--You are not logged in--> <!--<a href="{% provider_login_url "facebook" method="js_sdk" %}">Facebook Connect</a>--> {% endif %} {% if user.is_authenticated %} <a id="twitter_login" href="/accounts/logout"><button type="button" class="twitter__submit"> Log out<i class="fa fa-twitter" aria-hidden="true" style="font-size: 255%"></i></button></a> <!--<a href="/accounts/logout/"><div>Sign Out</div></a>--> {% else %} <a id="twitter_login" href="/accounts/twitter/login"><button type="button" class="twitter__submit btn-space"> Log in with<i class="fa fa-twitter" aria-hidden="true" style="font-size: 255%"></i></button></a> <!--You are not logged in--> <!--<a href="{% provider_login_url "facebook" method="js_sdk" %}">Facebook Connect</a>--> {% endif %} I am using Django-Allauth for the authentication in Django 1.11.5 with Python 2.7 I am not able to authenticate user with twitter as the program redirects to teh facebook link. Kindly, suggest me the improvement in my code so that the authentication will work separately. -
How to change letters in text to other letters | Python 2.7?
In my Django project I have form with field ("title"). In this field user need to write in Russian language but user can by mistake write some Latin letters. I want to change them. I use PYTHON 2.7. Next code raise error. How to fix this error? from string import maketrans eng = 'ETOPAHKXCBMetopahkxcbm' # English letters rus = 'ЕТОРАНКХСВМеторанкхсвм' # Russian letters def form_valid(self, form): form.cleaned_data['title'].translate(maketrans(dict(zip(eng, rus)))) form.save() ERROR: Traceback (most recent call last): File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/edit.py", line 217, in post return super(BaseCreateView, self).post(request, *args, **kwargs) File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/edit.py", line 183, in post return self.form_valid(form) File "/home/nurzhan/dashboard.kase.kz/static_pages/views.py", line 54, in form_valid form.cleaned_data['title'].translate(maketrans(dict(zip(eng, rus)))) TypeError: maketrans() takes exactly 2 arguments (1 given) -
how to integrate project in django + vue + webpack
I am very new in django frontend stuff. I want to make a front end in django + Vue js + Webpack. i follow this website https://ariera.github.io/2017/09/26/django-webpack-vue-js-setting-up-a-new-project-that-s-easy-to-develop-and-deploy-part-1.html to write but at the end i got this errors " url(r'^$', TemplateView.as_view(template_name='my_project/spa.html'), name='home'), NameError: name 'url' is not defined". I don't understand the problem. Could you please help me or give me suggestion on how to make a new project in django + vueJs+ Webpack with path and Directory. -
Python Class routing on data-flow processing
What is the most correct and "pythonic" way to deal with a class routing for many different type of objects. I have a data flow of many different json events that have to be processed, but every kind of event has a different json structure corresponding on a different class created to deal with it, what i want to do is to catch the event, read the descriptive field that identify the type e create a corresponding object with correct class, and with a wrapper catch all the values in the json structure, but not with an infinite series of " if....elif.........else". Any advice? Thank you PS it is inside a django project -
Django import issue when updating models
I have a problem when using import after updating one of my models I get the error ImportError: cannot import name 'Team' This was my actual model from django.db import models from registration.models import MyUser from django.core.urlresolvers import reverse # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) and I wanted to add the candidat_answer to the Project model from the Response model so I imported the models to be able to use it which gave me that actual code : from django.db import models from registration.models import MyUser from survey.models.response import Response from django.core.urlresolvers import reverse # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) candidat_answers = models.ForeignKey(Response) However now I get an import error from my registration import views .. from website.models import Team, Project ImportError: cannot import name 'Team' -
Is Django test Client can work with different domains?
Can i use Client for testing functional with, for example, different regional domains of project? I try: response = client.post(reverse('uri'), data={}, HTTP_HOST='domain1') response = client.post(reverse('uri'), data={}, HTTP_HOST='domain2') And i expected, that Client get different cookies for different domains, but in fact client get single cookie. Is any way to get different cookies in this case? Or only way use CI with silenium? -
Is there any way to run unittest from button click on django sites?
I have written unit tests as well the django documentation. I can run tests from python manage.py test. That's good. But, I want to run test from a button click. This button can be anywhere in my UI. Also I want to generate a simple report on passed or failed. Is it possible with Python/Django unittest module? -
How would you make an Excel-like user interface with Django?
I am currently working on a project where the user wants the user interface to look like an Excel document. This is because the user normally writes data into an Excel document, and wants to switch to writing data straight into the user-interface instead. It should look something like this: In this project, so far, I have only used Django, and there was no need for using Bootstrap, for example. However, I would be willing to use a front-end framework in order to create this Exel-like user interface. Trying to make html-tables have been unsuccessful so far. Does anyone have suggestions on how it might be done? Thank you! -
Convert datetime to local time from Django Query to Openpyxl
Django converts the date time (I use timezone.now() to store in database) to local time in templates fine. What I need help on is when it is written to a cell in openpyxl. Right now, I simply assign the attribute of the query to the cell. query = SomeModel.objects.latest() date_recorded = query.date_recorded In templates, date_recorded is already converted to local time. No problem there. ws.cell(row=rows, column=cols).value = date_recorded The above code results to UTC. Please help me convert it to local time. Thank you. -
Linear Scale Django form widget
I am looking for some guidance in order to create a widget that is not documented at all in the django documentation but is an evident part of forms. And I am talking about Linear Scales widgets for forms. Giving the ability to a user to choose on a scale between 1-100 a score If you have any idea on how to do it, any direction I would be please to get it ;) thx you very much -
Not able to access server when invoking gunicorn via .bash file
I am not able to access server when starting gunicorn via a .bash file I made. It works when I do it manually with this command $ gunicorn project.wsgi:application --bind 192.168.1.130:8000 Created a gunicorn.bash file from tutorials. I looks like this and runs without fault. #!/bin/bash NAME="project" # Name of the application DJANGODIR=/home/username/projects/project # Django project directory SOCKFILE=/home/username/.venvs/project/run/gunicorn.sock # We will communicate using this unix socket USER=username # the user to run as GROUP=username # the group to run as NUM_WORKERS=1 # how many worker processes shoul Gunicorn spawn DJANGO_SETTINGS_MODULE=project.settings.production # which settings file should Django use DJANGO_WSGI_MODULE=project.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/username/.venvs/project/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exsist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start yout Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use daemon) exec gunicorn ${DJANGO_WSGI_UNICORN}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- I don't know how to troubleshoot this? Maybe some command to see what differs in running settings from manually starting gunicorn and from … -
Getting status of task from Django Background Tasks
I am working with Django and i want to start some background tasks. I found the library "Django Background Tasks". It has almost everything I need but I can not find how to get the status of the task (pending/running/completed) anywhere in the documentation (http://django-background-tasks.readthedocs.io/en/latest/). It would be cery helpful for me if someone could tell me how to get the status of the task.