Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How can I do PATCH requests - ModelSerializer, RetrieveUpdateDestroyAPIView
I have a ProfileSerializer which is a ModelSerializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password') class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data, username=validated_data.get('username')) profile = Profile.objects.create(user=user, **validated_data) return profile def update(self, instance, validated_data): instance.dob = validated_data.get('dob', instance.dob) instance.karma = validated_data.get('karma', instance.karma) instance.username = validated_data.get('username', instance.username) user_data = validated_data.pop('user') instance.user.first_name = user_data.get('first_name', instance.user.first_name) instance.user.last_name = user_data.get('last_name', instance.user.last_name) instance.user.email = user_data.get('email', instance.user.email) instance.user.username = instance.username new_password = user_data.get('password') if new_password: instance.user.set_password(new_password) instance.user.save() instance.save() return instance class Meta: model = Profile fields = '__all__' And, I have a view named DetailProfile which is a RetrieveUpdateDestroyAPIView: class DetailProfile(RetrieveUpdateDestroyAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'username' lookup_url_kwarg = 'username' The problem with this is whenever I do a PUT request, I have to send all the fields including password. Now, the password that I obtain from GET request is hashed. So, If I send the same hashed password in PUT request, the password is getting replaced with that string (which looks something like this pbkdf2_sha256$100000$v7HiZeWnhmQj$ftiQyZCjMJ6pa26P5w72wQZvn+goEB94/lKyJ8LeKrM=). So, I want to make a PATCH request and not send password. -
Changing Return Type on Creation in Serializer
I have the following two serializers: class ProgramSerializer(serializers.ModelSerializer): class Meta: from radio.models import Program model = Program fields = ('id', 'title') class UserRecentlyPlayedSerializer(serializers.ModelSerializer): program_data = ProgramSerializer(read_only=True) class Meta: model = UserRecentlyPlayed fields = ('id', 'user', 'program', 'program_data',) They are based on the following models: class Program(models.Model): title = models.CharField(max_length=64) class UserRecentlyPlayed(models.Model): user = models.ForeignKey(User) program = models.ForeignKey(Program) What I'm trying to do is the following: On create, I want to be able create a new instance of UserRecentlyPlayed in the following manner: { "user": "...user id ....", "program": "....program id...." } However, when I return a list, I would like to return the following: [{ "id": "... id .... ", "user": ".... user id .....", "program": {"id": "...program id...", "title": "...title..." } }] These are called in the following view: class RecentlyPlayed(generics.ListCreateAPIView): serializer_class = UserRecentlyPlayedSerializer This, unfortunately is not working. What is the correct magic for this? -
Django send email from a CBV without having a model
I need to send with Django email when a user completes a contact form. Because the information, from the form is not kept in Django database, I don't have models for it, just get the information and send email. I'm using Class Based Views. I'm thinking of inheriting from View, but where(method) and how I hook my sending email ? Can I use just inputs(direct html form), or I need to create a Django form ? -
How to implement a FilteredSelectMultiple like the one in Django Admin?
I'm trying to create a FilteredSelectMultiple similar to the assigning of groups/permissions in the Django Admin at the user side. I've managed to get the interface widget to be displayed already (There's 5, one for each role). However I'm unsure of the back-end logic. I am currently using FormView for this. I would like to know: How to have the items displayed in the chosen the next time a user return How to have Django know what items were newly added into the list and what has been removed when I click on the Save button. An idea of mine was to have two lists: One that contains all the records already saved into the database (The items that should be displayed in the chosen the next time a user enters) and another list which is the latest one after a user saves (It contain newer elements and/or might have a few old elements removed). However I'm not sure if this is correct or if there is a better way. These are my codes (Apologies in advance, views.py is not yet complete so at the moment prints are used): forms.py: class DesignationForm(forms.ModelForm): class Media: css = { 'all': ('admin/css/responsive.css', 'admin/css/base.css', … -
unable to load dll from django
using windows 10 64 bit, 64 bit python 2.7, 64 bit dll I have dll written in C language. I converted to python using 'python ctypes' in a single file(assume test.py) where I faced no problem while loading the dll. Now I would like to load the dll from django project where I am facing the problem I got the exception like WindowsError: [Error 126] The specified module could not be found. Note: The above exception raises only when working django django -
Many to Many field Returning None django
When I try to print a field (Many-to-Many)in the terminal I only get the result "None". Am I missing something? view.py def assign_skill (request, pk): plan = get_object_or_404(Plan, pk=pk) if(request.GET.get('assign_skill')): print("nummer1") print(plan.title) print(plan.skillonplan) return redirect('all-plan') models.py class Plan(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False) subscriber = models.ManyToManyField(User, blank = True, related_name = 'plansubscriber') title = models.CharField(max_length=100, default = '', null=True, blank=True) description = models.TextField(max_length=10000, default = '', null=True, blank=True) company = models.CharField(max_length=200, null=True, editable=False) created_date = models.DateTimeField(default=timezone.now) skillonplan = models.ManyToManyField(Skill, null=True, blank = True, related_name='planneke') duration = models.IntegerField(default=0, validators=[MaxValueValidator(36), MinValueValidator(1)] ) def get_skills(self): return '\n'.join([p.skills for p in self.skill.all()]) def __str__(self): return self.title def get_absolute_url(self): return reverse_lazy('plan_detail', kwargs={'pk': self.id}) -
How to add React components to existing Django project
I want to add just React components to Django's template html file (not replace entire template with React as Frontend that there are a lot of tutorial on internet, just certain part of website) because that part of website require high interactivity which is easier to write it in React. I followed Add React to a Website tutorial to add JSX preprocessor. I set up project like this. /app-a /static /app-a <-- preprocessed files are here /templates /app-a index.html <-- Django template file that I want to include a react component to /app-b /react <-- this is where I wrote JSX files manage.py package.json And included React files at the end of index.html file like this. <html> <body> <div id="formContainer"> </div> <!-- React --> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <!-- my root React component file --> <script src="{% static 'app-a/App.js' %}"></script> </body> And I ran babel --watch to preprocess JSX files like this npx babel --watch ./react --out-dir ./app-a/static/app-a --presets react-app I thought it worked because whenever I saved JSX component files, they were preprocessed and output to /app-a/static/app-a. At the end of root JSX file, I included root React component to DOM like this. import React, { Component … -
Json loads error parsing
I'm coding in Django python and I want to decode a json string. In my view I'm doing the following : body = json.loads(request.body) Sometimes I'm getting the following error : json.decoder.JSONDecodeError: Invalid \uXXXX escape: line 1 column 218748 (char 218747) what is the problem? -
Exporting of Django tables2
I am trying to use the example of Django tables2 to export xls and csv. this is the part of my html: {% for format in table.export_formats %} <a href="{% export_url format %}"> download <code>.{{ format }}</code> </a> {% endfor %} My web page is class view based with filter, I can see my web url with query string attached with '?_export=xls', which is expected. However, when I clicked, no response, out output file created? not sure if anything else to make it work? My work is almost the same as this example, but no output created when clicked. Any ideas? thanks a lot. I am using django tables 2 and trying to export my table following the official documentation -
django.db.utils.OperationalError: (1045, u"Access denied for user 'my_user'@'localhost' (using password: NO)")
I am trying to connect to MySQL from DJango. My settings.py file: DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.mysql', 'Name': 'my_db', 'User': 'my_user', 'Password': 'my_pass', 'Host': 'localhost', 'Port': '3306' } } } I am getting following error. django.db.utils.OperationalError: (1045, u"Access denied for user 'my_user'@'localhost' (using password: NO)") I have tried following steps to solve the problem. I have created the user: create user 'my_user'@'localhost' identified by 'my_pass'; And granted access as follows: grant all on *.* to 'my_user'@'localhost'; flush privileges; But, even though my problem not yet fixed. Can someone help me? Thanks. -
Django URL didn't match any of these
I'm writing a programme, in an env as python3.5 and django2.0. Something wrong with URLconf. I want to ask a url like this: 192.168.9.6:8080/gene/1956/variant_desc.html and I get this error: admin/ gene/ [name='index'] gene/ <int:gene_id>/ [name='detail'] gene/ <int:gene_id>/variant [name='variant'] gene/ <int:gene_id>/variant_desc [name='variant_desc'] gene/ (\d+)/variant_desc I think my url can match the 5th one, or the 6th one, however none of them could match. What's wrong with it? And here is HTML code: <ul> {% for item in gene_variant %} <li> <a href="variant_desc.html"> {{item.gene_variant}} </a> </li> {% endfor %} </ul> Thank you guys! -
Django 2.1 NOT NULL Constraint Failed When Creating Super User
I've been using Django for several months now without any issue but when I went to create a new project and add the super-user, I get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: auth_user.last_login All migrations have been created and applied successfully. I have destroyed and recreated the database a half dozen times to no avail. App migrations run without any problem whatsoever and this is the first time I've encountered this issue in an Django project. -
Upgrading pip/installing django - [SSL: TLSV1_ALERT_PROTOCOL_VERSION]
I am having issues with installing django and upgrading pip. I don't know how I began running into these issues, but when I go to type django-admin startproject mysite it gives me an error: -bash: django-admin: command not found I go ahead and type pip install Django and I then receive this error: Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping When upgrading pip... Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping I believe the issue lies within [SSL: TLSV1_ALERT_PROTOCOL_VERSION]. I don't know how to go about fixing it so that I can use django and upgrade my pip version. If I type python3 -c "import ssl; print(ssl.OPENSSL_VERSION)", I get OpenSSL 1.0.2n 7 Dec 2017. Do note that I was running django with no issues before these issues came to fruition. -
Saving FieldIn Django Via API Call
I'm trying to create a new CustomerDetail object whenever an api is called.But the issue is, Whenever I try to create something for the favorite meal multi-selectfield, I get this error: MultiValueDictKeyError at /api/customer/favorite_meal/ "'favorite_meal'" This is the api: @csrf_exempt def favorite_meal(request): if request.method == "POST": access_token = AccessToken.objects.get(token = request.GET.get("access_token"), expires__gt = timezone.now()) customer = access_token.user.customer details = CustomerDetailSerializer( CustomerDetails.objects.create( customer = customer, favorite_mean = request.POST["favorite_meal"] )) return JsonResponse({"status" : "success"}) Here are my models: class CustomerDetails(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer') TYPE = ( ('Time', ( ('Breakfast', 'Breakfast'), ('Lunch', 'Lunch'), ('Dinner', 'Dinner'), )), ) favorite_meal = MultiSelectField(choices=TYPE) interested_in = MultiSelectField(choices=CATEGORIES) likes = models.ManyToManyField('Product') completed_orders = models.IntegerField(default = "0", blank=True) shares = models.IntegerField(default = "0", blank=True) average_order = models.FloatField(default = "0.0", blank=True) def __str__(self): return self.customer.user.get_full_name() In the request, I'm trying to select breakfast and lunch via the api. How would I do this? -
Django: which type of relation to use, if model have many-to-one relation with several other models?
I.e. we have model File, which can be attached to Email and putted to FileCollection. So Email can contain several File so as FileCollection. If I understand well 2 external tables File2Email and File2FileCollection should be used. How it's managed in Django? Which keywords to google? -
django - where can i clean the data of a formset?
I have a view function where I have two forms, one to create a post and the other is a formset to save images. Where can I clean the data of the formset? I want to resize the images to a particular size. Can i create a class for the formset similar to a class? @login_required(login_url='/accounts/login/') def postCreateView(request): ImageFormset = modelformset_factory(Image, fields=('image',), extra=3) if request.method == 'POST': form = PostCreateForm(request.POST) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): post = form.save(commit=False) post.user = request.user post.save() for f in formset: try: photo = Image(post=post, image=f.cleaned_data['image']) photo.save() except Exception as e: break return redirect('posts:post_list') else: form = PostCreateForm() formset = ImageFormset(queryset=Image.objects.none()) context = { 'form': form, 'formset': formset, } return render(request, 'posts/post_form.html', context) -
how to redirect back to the same page in a RedirectView Django
I have the below view I am trying to Redirect the user to the same page class TastingPickedToggle(LoginRequiredMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): pk = self.kwargs.get('pk') obj = get_object_or_404(OrderItem, pk=pk) user = obj.order.buyer if user in obj.picked.all(): obj.picked.remove(user) else: obj.picked.add(user) return redirect('order:tasting_sold_orders') but I get a Page not found (404) error. below are my urls.py urlpatterns = [ url(r'^tasting_sold_orders/$', views.TastingsSoldOrders.as_view(), name='tasting_sold_orders'), url(r'^(?P<username>[-\w]+)/(?P<pk>\d+)/pick/$', views.TastingPickedToggle.as_view(), name='pick'), below are my templates.py {% if order.order.buyer in order.picked.all %} <a href="{{ order.get_picked_url }}"><button class="btn btn-success">Picked</button></a> {% else %} <a href="{{ order.get_picked_url }}"><button class="btn btn-default">Not picked</button></a> {% endif %} The logic works. If I go back and refresh the button colors have changed. how can I get the return redirect to work -
How to access a model attribute across all templates?
I have a model team with attribute name: class Team(models.Model): name = models.CharField(max_length=50, null=True, blank=True) I want to put the team name in the header of the website, as in my template language would be something like: {% if team.name %} <h1>{{ team.name }}</h1> {% endif %} However the name only displays if I'm on a view that makes a query on the team model. So I guess I need to have that query available across all views/templates. What is the best way of going about this? -
One-to-one and Many-to-one relationships with the same pair of models
I have a Profile model and Photo model. Each profile has photos (One-to-many relationship) and a profile photo (One-to-one relationship). When I try to do this on django I get the error NameError: name 'Photo' is not defined because I'm referencing the model before it's defined. class Profile(models.Model): name = models.CharField(max_length=50, primary_key=True, blank=False) profile_photo = models.OneToOneField( Photo, null=True, on_delete=models.SET_NULL ) class Photo(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) photo = models.ImageField(primary_key=True, upload_to='photos/') A possible solution could be using a boolean field on Photo to specify if it's a profile photo or not, but I think that's inefficient because I'd have to query all photos of the profile and make a loop to find the profile photo. Are there a better solution for that? -
Passing data from conditional/chained drop boxes in a form to a view or directly to URL
I am in the process of implementing a feature to allow users to query, through a set of conditional drop boxes, to find other users by grouping. For example, my drop downs chain from Departments->Teams->Users. I have that part setup correctly, but I can't figure out how to use the data from the last (Users) to either send it to my view or redirect the user to a URL. If the user is test I want to send them to http://example.com/user/test or I want to send them to my view which accepts user as a parameter. I have a FormView, form, and 2 functions which work with Ajax to get the conditional drop boxes. See below for my code: Views.py class UserQuery(FormView): template_name = 'people/users_form.html' model = People form_class = UsersListForm def load_teams(request): department = request.GET.get('department') teams = Teams.objects.filter(department=department).order_by('team') return render(request, 'people/team_dropdown_list_options.html', {'teams': teams}) def load_users(request): team = request.GET.get('team') people = People.objects.filter(team=team).order_by('people') return render(request, 'people/people_dropdown_list_options.html', {'people': people}) def load_one(request): selected_person = request.GET.get('people') one = People.objects.get(id=selected_person).people return render(request, 'index.html', {'username': one}) So load_one() has the data I need. It has the username that I want to pass to http://example.com/user/{} -- I have a view already for that URL, but I need … -
Firefox Django CSRF token error
I recently made some changes to a form to do some more advanced error checking than celery provides (errors based on input from multiple fields). Everything was working fine until a coworker found that the form didn't work on Firefox anymore (dev and testing done on Chrome). The specific error being thrown is: django.request [WARNING] > Forbidden (CSRF token missing or incorrect.): /[url] I suspect the root of this issue comes from the change: <form action="{% url '[submit url]' %}"> to <form onsubmit="sendData()"> where sendData constructs an XMLHttpRequest and sends it. I've tried adding csrftoken header to the request from {{csrf_token}} but it fails for the same reason - and even breaks the process on Chrome! -
Best approach for quiz app in Django
I am wondering what the best approach is for a personality quiz. Users take a quiz, answer questions, then app will give response based on answers. My biggest question is whether or not I should use Django Forms. Below is my Model structure: class Quiz(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name class Question(models.Model): question_text = models.CharField(max_length=200) quiz = models.ForeignKey(Quiz) def __str__(self): return self.question_text class Choice(models.Model): quiz = models.ForeignKey(Quiz) question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return self.choice_text class Participant(models.Model): first_name = models.CharField(max_length=55) last_name = models.CharField(max_length=55) email = models.EmailField() date = models.DateTimeField(auto_now_add=True) quiz = models.ForeignKey(Quiz) def __str__(self): return self.first_name + self.last_name + " | " + self.email class QuestionAnswers(models.Model): quiz = models.ForeignKey(Quiz) question = models.ForeignKey(Question) choice = models.ForeignKey(Choice) participant = models.ForeignKey(Participant) So I have a quiz, then question, then choices that belong to that. So I'm not sure if I should render the forms in a template then do the logic in my view only, or use the Form class from Django to help with generating this. I'm also unsure of the best way to use the Form class if so. I have looked into formset_factory so that may be the best route. -
Django - Cannot filter by foreign key first_name
So currently im making so, you can search users that are attending an even, by some filters that are first_name, last_name, username The error is currently too many values to unpack (expected 2) How can I successfully search by the filters? My views.py: def volunteer(request): ## init context context = {} ## Get filters if somes searchfilter = request.GET.get('filter', None) searchinput = request.GET.get('searchinput', None) ## Checks if filter is not none or null or empty if searchfilter != "" and searchfilter != None and searchinput != "" and searchinput != None: ## Great now check what filter is used ## Now strip the filters for whitespaces searchfilter.strip() searchinput.strip() ## This filter is for teams if searchfilter == "teamname": teamsearch = Team.objects.all().filter(name__contains=searchinput) context['teams'] = True context['search'] = teamsearch ## This filter is for users elif searchfilter == "first_name" or searchfilter == "last_name" or searchfilter == "username" or searchfilter == "phone": makefilter = "user__"+searchfilter+"__contains="+searchinput usersearch = TeamMembership.objects.filter(makefilter) print(usersearch) context['users'] = True context['search'] = usersearch return render(request, 'volunteer/hqvolunteer.html', context) My model im trying to search user model are standard Django auth: class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) ingroup = models.BooleanField(default=False) leader = models.BooleanField(default=False) groupleader = models.BooleanField(default=False) -
Django-Channels capabilities
I'm trying to build a multiplayer, fast-paced, side-scrolling platformer game called Star Jumper using vanilla-js on canvas and Django-Channels for websockets. I'm having trouble getting enough messages through the server to make the lag playable. Messages sent to the server include key-down/up, mouse clicks and periodic reconciliations. To troubleshoot I focused on just the periodic reconciliation, setting up 2 counters on the redis-server within consumers.py - (1) reconciliation received from client and (2) reconciliation sent to the opposing client. With 2 players in the game, the server's messages received counter starts to outpace the messages sent counter at around 10 per second (2 players, 20 total per second). I'm hoping that I'm just doing something wrong, that Django Channels can handle more than 20 total messages per second, but I'm stumped. Relevant code is below, repo is here, happy to clarify/post more. Within the repo, the "play.html" template has my animation loop and socket traffic management. within "StarJumper/templates/play.html"... let socket = new ReconnectingWebSocket(ws_path) function Reconcile() { socket.send(JSON.stringify({ "command": "reconcile", "game": {{ game.id }}, "client_now": global_now, "current": { "x_pos": world.player.x_pos, "y_pos": world.player.y_pos, "vy": world.player.vy, "color": world.player.color, } })) } within "StarJumper/app/consumers.py"... async def receive_json(self, content): game = await get_game_or_error(content["game"], self.scope["user"]) command … -
django manage.py error with fabric2
Here is my script : #!/usr/bin/env python #-*- coding: utf-8 -*- from fabric2 import Connection c = Connection('nanic.hopto.org') with c.cd('/home/bussiere/Stack/Event/'): c.run('git pull origin master') c = Connection('nanic.hopto.org') with c.cd('/home/bussiere/Stack/Event/'): c.run('python3 manage.py runserver 0.0.0.0:8004') c = Connection('nanic.hopto.org') with c.cd('/home/bussiere/Stack/Data/'): c.run('python3 manage.py runserver 0.0.0.0:8005') And here is the error : From gitlab.com:bussiere/Event * branch master -> FETCH_HEAD Already up-to-date. Traceback (most recent call last): File "fabRelaunch.py", line 12, in c.run('python3 manage.py runserver 0.0.0.0:8004') File "", line 2, in run File "/usr/local/lib/python3.5/dist-packages/fabric2/connection.py", line 30, in opens return method(self, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/fabric2/connection.py", line 582, in run return self._run(runner, command, **kwargs) File "/usr/local/lib/python3.5/dist-packages/invoke/context.py", line 101, in _run return runner.run(command, **kwargs) File "/usr/local/lib/python3.5/dist-packages/invoke/runners.py", line 271, in run return self._run_body(command, **kwargs) File "/usr/local/lib/python3.5/dist-packages/invoke/runners.py", line 404, in _run_body raise UnexpectedExit(result) invoke.exceptions.UnexpectedExit: Encountered a bad command exit code! Command: 'cd /home/bussiere/Stack/Event/ && python3 manage.py runserver 0.0.0.0:8004' Exit code: 1 Stdout: already printed Stderr: already printed Any idea why i have an error when trying to launch my django ? thanks