Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - remove primary_key=True from an existing model?
I have a table that I've already migrated into the MySQL database and one of the fields has primary_key = True. I realized this needs to be different and I need to remove the primary_key = True. I'd like Django to create its own auto incrementing primary key fields (like it does with all models if you don't specify a primary_key). If I simply remove the primary_key = True, Django complains because it can't auto-assign an auto-increment value to its new id field (which is now the primary key field). What's the best way to change this one field to not have primary_key = True? This particular model doesn't have any records yet in the database, so I think I'm in a better position than if I had records in there. I'm not sure if I should just drop the table and migrate as if it's a brand new table or if I need to take some other approach? -
Webpack 3.1. jQuery is added multiple times
After migration to Webpack 3, I have noticed that jQuery inclusion works not as I expected. My template structure has core/_global.html root template in which I render common js and css assets like: <head> {% render_bundle 'global' 'css' %} {% block stylesheets %}{% endblock %} {% render_bundle 'global' 'js' %} {% block header_javascripts %}{% endblock %} </head> Second level templates extend the root template and add additional js and css to html: {% extends "core/_global.html" %} {% load render_bundle from webpack_loader %} {% block stylesheets %} {% render_bundle 'accounts/register' 'css' %} {% endblock %} {% block javascripts %} {% render_bundle 'accounts/register' 'js' %} {% endblock %} In previous verions of Webpack at the beginning of global.js I had: import 'expose?jQuery!expose?$!jquery' After removing this line and changing webpack.config to: plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", }), I have following problem - each of the rendered files, global.js and register.js contain jQuery. As result the size of each file is increased by appr. 300 kb. I expect jQuery should be loaded only once and it should be accessible both in global.js and register.js Are there any workarounds which allow to include jQuery in such way and have access to it … -
How best would I keep track of frontend version in a Django app?
I currently deploy frontend and backend together, but I'd like to split them into two independently deployable components. For the backend I use Django. What I'd like to know is how best to manage versioning from Django. For example, I have just pushed a new frontend deploy, which means I now have a new bundle-{VERSION}.js sitting in S3, where {VERSION} is the commit-hash. I now need to update Django to serve new pages so that {VERSION} is correctly sent down with templates. What's the best way to store a global variable like this, in such a way that it can be updated easily? I don't want to add a database hit to every pageload, so storing in the database is not ideal. I could save it to a file, but that's not great either. In order to use settings.py, I'd have to restart the server process every time I deploy the frontend, which is not ideal. Is there a way of storing the version so that it's stored in memory in the server process, but it can be updated easily? -
Django-IIS - FastCGI exited unexpectedly
I am encountering this FastCGI exited unexpectedly and I do not know how to resolve this error. I have looked around stackoverflow for solutions but the either the suggested solutions don't apply or no answers provided to the question. I want to run very basic django website (in fact I just created it) using IIS server with WFastCGI. Here is my spec: IIS 10.0 Windows Server 2016 Django 1.11.4. Python 3.6.2 wfastcgi 3.0.0 My python installation is in C drive. I am creating a virtualenv in D drive and pointing path to virtualenv's Python when configuring. When I point to virtualenv's Python, this error 'FastCGI process exited unexpectedly'. If I point my path to C's python, this error disappears (There is another python cant find module error but I can resolve that). I do not know the reason for this fastcgi exited issue when I use virtualenv's python. Kindly enlighten me if possible. Here is the detailed error info: Module FastCgiModule Notification ExecuteRequestHandler Handler djangohandler Error Code 0xc0000135 Requested URL http://localhost:8089/ Physical Path D:\inetpub\django\foo Logon Method Anonymous Logon User Anonymous -
Django REST Framework - OneToOne Relation through JSON
I want to create an API that allows to send JSON through a POST request. The JSON should then get passed on to a serializer which takes care of creating a new object and populate it with the existing data. It works fine for the 'simple' cases such as basic character-only inputs like usernames and alike, but I am seriously stuck when it comes to creating a OneToOne relation. Here's the sample code. Function called employee_list in views.py - data['account'] is a valid username, a User instance is successfully being selected! data = JSONParser().parse(request) user_object = User.objects.get(username=data['account']) data['account'] = user_object # this is now a valid User object serializer = EmployeeSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) The model class Employee(models.Model) id = models.AutoField(primary_key=True) name = models.CharField(...) surname = models.CharField... account = models.OneToOneField(User) role = ... salary = ... picture = ... And the serializer class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = (...) # all fields of the `Employee` model So far so good, however, the serializer never validates! When I remove the need for a OneToOne relation, it works.. How can I create a new Employee objects with a working OneToOne relationship to a … -
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?