Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pre-populate the correct choice for a CharField in a Django form
I have a model which contains a CharField consisting of choices as in the example below class SomeModel(models.Model): some_field = models.CharField(choices=(('Name1', 'Name1'), ('Name2', 'Name2') ('Name3', 'Name3') ) ) Here is my ModelForm class SomeModelForm(forms.ModelForm): class Meta: model = SomeModel Here is my basic view which attaches an instance to the form: def some_view(request, model_id): somemodel = SomeModel.objects.get(id=model_id) form = SomeModelForm(instance=somemodel) context = {'form': form} return render(request, 'page.html', context) When the form is rendered the dropdown is not pre-populated. It is not a case of something being wrong with my code as all other form fields (omitted from this example) ARE pre-populated. I know I could make the CharField a ForeignKey and then Django would pre-populate the dropdown correctly but I don't want to do this. Is there any way to make the form show the correct choice? Any help would be greatly appreciated! -
Django REST Framework: nested relationship, how to submit json?
I'm using Django 2.1, DRF 3.7.7. I've some models and their relative (model) serializers: these models are nested, and so are the serializers. Let me give an example: # models.py class City(models.Model): name = models.CharField(max_length=50) class Person(models.Model): surname = models.CharField(max_length=30) birth_place = models.ForeignKey(City) # serializers.py class CitySerializer(serializers.ModelSerializer): class Meta: model = models.CitySerializer fields = "__all__" class PersonSerializer(serializers.ModelSerializer): birth_place = CitySerializer() class Meta: model = models.Person fields = "__all__" I only need to get data from the endpoints connected to the serializers, I don't need to write anything on the REST interface, since the POST processing of the form is done by Django. If I submit an AJAX request with a json like: {'surname': 'smith', 'birth_place': 42} I get back a Bad Request response, containing: Invalid data. Expected a dictionary, but got int. If I submit a nested json like: {'surname': 'smith', 'birth_place': {'id': 42, 'name': 'Toronto'}} the relation is not converted, the id field is ignored and the rest is parsed to: OrderedDict([('birth_place', OrderedDict([('name', 'Toronto')]))]) The following is the post method I'm using on a class-based view: def post(self, request): print("Original data:", request.data) serializer = self.serializer_class(data=request.data) if serializer.is_valid(): self.data = serializer.validated_data print("Parsed data:", self.data) ... TL;DR: How should I correctly … -
How to activate JavaScript before the next page starts to load?
I want to make a loading screen that appears when someone submits a Django form. Here's some example code: forms.py class ExampleForm(forms.Form): example_field = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}) ) index.html <style> .overlay { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(255,255,255,0.8); z-index: 5000; text-align: center; padding-top: 20%; } </style> <form action="example_form"> {% for each in example_form %} {{ each.label_tag }} {{ each }} {% endif %} <button type="submit" class="btn btn-primary" name="action" value="submit">submit</button> </form> <script> $(document).ready(function () { function ShowLoading() { $(".overlay").show(); } $("button[type='submit']").on("click", ShowLoading) }) </script> This code successfully has a loading screen appear when the submit button is clicked and before the next page loads. However, the problem comes when you don't enter anything in it's single required field but click on submit anyway. What happens is that a tooltip that tells the user to enter an input will appear, but the loading screen will appear anyway even though it's not actually loading another page. This is because it activates by click and not whether or not the next page starts loading. What I want is instead of the JavaScript activating on button click, I want it to activate when the next page is … -
Django 'title_en' is not in list
Request Method: GET Request URL: http://localhost:8000/blog/blog-title/ Django Version: 1.10.8 Exception Type: ValueError Exception Value: 'title_en' is not in list Exception Location: /lib/python3.6/site-packages/django/db/models/query.py in __init__, line 1715 Python Executable: /bin/python Python Version: 3.6.5 after installing django-modeltranslation i am getting this error on my django site. I have tried adding fields in translationOptions. Also tried makemigration and migrations. This adds the title_en in table however it's not rendering the blog on the front. Before adding django-modeltranslation the blogs were being rendered properly without any error. -
Django Query to Aggregate the Sum for Matching Instances in the Same Field
I have the following Django (2.1) model: class Sales(models.Model): product_name = models.ForeignKey(Product) category = models.ForeignKey(Category) sales= models.DecimalField(max_digits=25) I would like to receive the sum of all sales for each different product_name instance that is the same. For example, I have the following sales by product_name: DVDs = 6.00 DVDs = 6.00 Books = 14.00 Books = 6.00 Magazines = 4.00 Magazines = 4.00 I can use Sales.objects.aggregate(sales=Sum('sales')) to get the total aggregate of all sales instances combined but how can I get the aggregate for product_name separately; i.e. Books ($20.00), DVDs ($12.00), Magazines ($8.00)? -
How to get (Login logic) customer data by passing customer mobile and password on Django Rest Framework
I am a newbie to django rest framework. so i need to write the Post method for getting the customer details by using customermobile(User name) and customerPassword(password). I read the filter concept but i don't have the luck. models.py class Customer(models.Model): Status = Choices( (0, 'Deleted'), (1, 'disabled'), (2, 'active'), ) customerID = models.AutoField(primary_key=True) companyID = models.ForeignKey(Company, on_delete=models.CASCADE) firstName = models.CharField(max_length=200, null=False) lastName = models.CharField(max_length=200, null=True) customermobile = models.CharField(max_length=20, null=False) customerpassword = models.CharField(max_length=20, validators=[MinLengthValidator(8)], null=False) customeremail = models.CharField(max_length=1000, null=True) tocken = models.CharField(max_length=35, default=str(uuid.uuid4().hex)) createdBy = models.IntegerField(null=False) createdAt = models.DateTimeField(null=False, auto_now=True) status = models.IntegerField(choices=Status, default=2) updatedBy = models.IntegerField(null=True) updatedAt = models.DateTimeField(null=True, auto_now=True) def __str__(self): return "{}".format(self.firstName) Serializers.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = customer fields = ('companyID', 'firstName', 'lastName', 'customermobile', 'customerpassword', 'customeremail', 'tocken', 'createdBy', 'createdAt', 'status', ) read_only_fields = ('createdAt',) views.py class CustomerList(APIView): """List all Customer or create the new customer""" def post(self, request, format=None): customerSerializer = CustomerSerializer(data=request.POST) if customerSerializer.is_valid(): customerSerializer.save() return Response(customerSerializer.data, status=status.HTTP_201_CREATED) return Response(customerSerializer.errors, status=status.HTTP_400_BAD_REQUEST) class CustomerFilter(django_filters.FilterSet): class Meta: model = Customer fields = ['customermobile', 'customerpassword'] class Login(APIView): def post(self, request, format=None): customer = Customer.objects.all() customeFil = CustomerFilter(request.POST, queryset=customer) If anyone knows the solution please let me know here. Thanks -
Django - get URL from TemplateResponse
I have a Django app that uses the builtin login system. I'm trying to write a unit test that verifies that the login url redirects to home if the user is already authenticated. I know how to do this, and have manually verified that it's working. However, I'm not sure how to write a unit test for this. Question: how do I get the URL from a TemplateResponse? Django's builtin LoginView returns a TemplateResponse, which doesn't have a url parameter. What I have so far is this: from django.test import TestCase from django.urls import reverse home = reverse('home') login = reverse('login') logout = reverse('logout') signup = reverse('signup') USER_CREDS = { some user's credentials } class TestLoginView(TestCase): def test_login_redirect(self): self.client.post(signup, USER_CREDS) self.client.get(logout) self.client.post(login, USER_CREDS) response = self.client.get(login) self.assertEqual(response.url, home) This results in: AttributeError: 'TemplateResponse' object has no attribute 'url' -
I dont know why my authenticate method is not working
I have a django project in which it has a custom user model, and I am able to use it to login properly. But, in my registration form, I have the same code for logging the user in after he registers, but it doesn't actually log the user in, just create the account. Please try to help me see what I am doing wrong. And if theres any way I can improve my code, please let me know. Follows the code for the registration form, which register the user but doenst log it in. If anybody needs any extra piece of code, please ask me. Thanks ahead! class UserFormView(View): form_class = UserForm template_name = 'scheduling/registration_form.html' user = get_user_model() #display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns User objects if credentials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return render(request, 'scheduling/index.html', {}) #return redirect('scheduling:index') return render(request, self.template_name, {'form': form}) Now, there's the code for the login, which is exactly the same … -
How to edit requested params in Django Admin Page?
By default Django admin page, basically form submitted data set to database naturally without any data edit. However I want to edit this. When I develop blog to use Django admin, I have columns in table like this | title | article_md | article_html | posted_date | edited_date | and I want to make article_html data not to edit directly in django admin page form but generate from markdown style data of article_md to HTML style and submit to database. How can I do this? Is there any way to do something like generally controller in model.py or admin.py? -
How to import my django app's models from command-line?
I would like to be able to manipulate my Django app's models via the python console. I am able to do this with PyCharm but I do not have access to PyCharm in this scenario. I tried this: [root@myhost scripts]# source /apps/capman/env/bin/activate (env) [root@myhost scripts]# python Python 2.7.14 (default, Jan 9 2018, 20:51:20) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> from vc.models import * But I get the error: Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named vc.models What am I doing wrong? -
Can make initial django migrations run
So I have this django project from elsewhere (I didn't develop it). It's setup to run in docker, I get everything up and running in my fresh environment and bash into the django docker container. I try running migrations python manage.py migrate. Gives InconsistentMigrationHistory error. I try running migrations for different apps at the same time. I keep getting the errors. Maybe important, but some of the errors are circular. IE running migrations on app a, says it depends on app b, running it on b says it requires app a. So I blow away the docker containers and rebuild everything. This time I delete all the migrations before I do anything and run python manage.py make migrations first. This runs fine. Then when I migrate I get the same error, only this time it's a Migration admin.0001_initial is applied before its dependency error (originally was a specific app). I've been using docker for awhile but I don't think I've really delved totally into what it's capable of. So the only thing I can think of is maybe deleting and rebuilding the container isn't resetting the database? Just in case, here are the steps I took (four containers run and … -
How to customize Django Admin delete UI?
The Django Admin delete UI is a bit confusing and intimidating. I need to customize it a bit: Change the label of the delete button to Delete + model.verbose_name. For example: Delete Pet Change the delete warning message to something more friendly. The default message is too intimidating. It has a warning message, a summary of models and objects being affected. Instead, I just need a simple warning message such as "Are you sure you want to delete the Pet My Puppy"? What is the best way to achieve this? (Django 1.11) -
Django2 and Angular2 url integration problem with parameters
I have an url with parameters. Angular tries to make a call to it but django waits and slash after the url and angular adds a question mark before the parameters. How can I integrate both? Thanks -
Django 2 - Could not parse the remainder: ' 'upvote.png'' from 'static 'upvote.png''
I am having a issue regarding static files and Django. My main project is called "produchunt" (it is a clone of the real website) which contains "account" and "products". I successfully add a static folder in "producthunt" for static file. Now, I am trying to add a "upvote" image on the products app. I did the following: Add the image on the static folder of the main app "producthunt" Write the template of "products" Run python3 manage.py collectstatics BUT I am having this error: Could not parse the remainder: ' 'upvote.png'' from 'static 'upvote.png'' The urls.py in "producthunt" is: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('accounts/', include('accounts.urls')), path('products/', include('products.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The settings.py in "producthunt" is: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'producthunt/static/'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' The url.py in "products" is: from django.urls import path, include from . import views urlpatterns = [ path('create', views.create, name='create'), path('<int:product_id>', views.detail, name='detail'), ] The temaplte "detail.html" of "products" is: <img src="{{ static 'upvote.png' }}" alt="Upvote"> However, I am having the error: Could not parse the remainder: ' 'upvote.png'' from 'static 'upvote.png'' Many thanks -
AttributeError: 'Query' object has no attribute 'contains_aggregate'
I'm making a Django app and I have a view that display both sides of an object_set (a reverse many to many). Because of this, I want to query all of the objects on both sides at the same time. Specifically speaking, I want to have all of the Signup objects that are associated with each Event. (The view page format should look like this.) Event (0) -- Signup (0.0) -- Signup (0.1) -- Signup (0.2) -- Signup (0.3) Event (1) -- Signup (1.0) -- Signup (1.1) Event (3) -- Signup (3.0) -- Signup (3.1) -- Signup (3.2) -- Signup (3.3) ... The code is as follows: class TournamentDetailView(DetailView): model = Tournament def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) tournament_id = self.get_object().pk events = Event.objects.annotate( cached_signups=( Signup.objects .filter(event_id=OuterRef('pk'), tournament_id=tournament_id, dropped=False) .order_by('created') .defer('tournament') ) ).all() context['events'] = events return context Here's the traceback: Traceback: File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch 89. return handler(request, *args, **kwargs) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\detail.py" in get 106. context = self.get_context_data(object=self.object) File "C:\Users\werdn\PycharmProjects\gwspo-signups-website\gwhs_speech_and_debate\tournament_signups\views.py" in get_context_data 171. … -
How to store a lot of settings in a model with one field?
I have a model called Customizer. I want to offer users to customize a website. I don't want to add a field for every single setting because this model will have a lot of settings for example: Prefered color theme: red border right color: green background color: black button color xy: red etc. What is the best way in Django to do this? I know there is a JsonField in Django but I don't know if this is the correct way to store this data. -
Obtain special characters from 'model.object.raw(sql_query)'
I obtain several rows from a consult like this: object = model.object.raw("select * from table where field1 = 'something'") so I pass the result object as context to my page.html like this: return render( request, 'page.html', context_instance = RequestContext(request, { 'title':'something', 'result': object }) ) Then I represent the result in a table like this: ` <tbody> {% for r in result %} <tr> <td>{{f.field1}}</td> <td>{{f.field2}}</td> </tr> {% endfor %} </tbody> ` so let's say in some rows 'field2' the text have acsents or ñ characters like 'ó' so in my page that cell got blanks ***How can I show that type of characters?* -
Why is my binary data bigger after getting it from the webserver?
I need to serve a binary file through a web service implemented in Python/Django. The problem is, that when I compare the original file with the transferred file with vbindiff I see trailing bytes on the transferred file, sadly rendering it useless. The Binary File is accessed saved by a client in Java with: HttpURLConnection userdataConnection = null; URL userdataUrl = null; try { userdataUrl = new URL("http://localhost:8000/app/vuforia/10"); userdataConnection = (HttpURLConnection) userdataUrl.openConnection(); userdataConnection.setRequestMethod("GET"); userdataConnection.setRequestProperty("Content-Type", "application/octet-stream"); userdataConnection.connect(); InputStream userdataStream = new BufferedInputStream(userdataConnection.getInputStream()); try (ByteArrayOutputStream fileStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[4094]; while (userdataStream.read(buffer) != -1) { fileStream.write(buffer); } byte[] fileBytes = fileStream.toByteArray(); try (FileOutputStream fos = new FileOutputStream("./test.dat")) { fos.write(fileBytes); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } I think that HttpURLConnection.getInputStream only reads the body of the response, or not? This code serves the data in the backend in views.py: if request.method == "GET": all_data = VuforiaDatabase.objects.all() data = all_data.get(id=version) return FileResponse(data.get_dat_bytes()) in models.py: def get_dat_bytes(self): return self.dat_upload.open() How do I go about transferring the binary data 1:1? -
Django-simple-history error setting ChangeReason
I am using Django-simple-history version 2.3.0 with Django 2.0 and Python 3.6. I am comparing the previously existing data with the new data(comparing to serializer.validated_data) that is received via PUT request, comparing fields and making a list of changes. I am trying to add this list to my changeReason. My first attempt of saving the serializer and then calling an update results in 2 entry in the database. I tried to follow the docs and set as suggested there, but I get the following errors: AttributeError: 'NoneType' object has no attribute 'history_change_reason' when I try to pass the changeReason explicitly using update_change_reason or AttributeError: 'PatientSerializer' object has no attribute 'id' when I try it implicitly. My question: How do I update the changeReason and also have only 1 entry in the database. Here is my code for the View: class PutDetailsView(APIView): """ View used sending response for successful patient update """ permission_classes = [ permissions.IsAuthenticated ] serializer_class = PatientSerializer def put(self, request): is_many = True if isinstance(request.data, list) else False try: patient = Patient.objects.get(pk=request.data['ID']) except Patient.DoesNotExist: return Response({"status": 0, "error": "Patient does not exist"}, status=status.HTTP_404_NOT_FOUND) serializer = PatientSerializer(patient, data=request.data, many=is_many) if serializer.is_valid(): patient = Patient.objects.filter(pk=request.data['ID']).values() my_dict = {} for keys … -
UnicodeDecodeError sending mail Django
i'm trying to send email(doesn't matter what includes) usig send_mail function from from django.core.mail and it shows me this error all the time: UnicodeDecodeError at /mail 'utf-8' codec can't decode byte 0xf3 in position 8: invalid continuation byte Here's my vies.py and setting.py fiels def sendSimpleEmail(request): send_mail(subject='asda', message='asdas', from_email='example@test.com', recipient_list=['example2@test.com']) return redirect('home') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smpt.gmail.com' EMAIL_HOST_USER = 'test@example.com' EMAIL_HOST_PASSWORD = 'test' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Graphene_Django: How to send error messages or custom data
Using graphene_django to and of course GraphQL and I can't figure out how to send a good error message or better yet, how could I create custom messages to send back to the client. For a situation where someone tries to create an account but the email address has already been registered I'd like to send back something like: { "data": { "error": { "statusText": "This email address is not available", "statusCode": "401" // or whatever the status code is } } } Any help is much appreciated. -
Django tastypie: User sees no data
I want to add authentication to my API, so only authorized people can see the data. To my resource class I added: authentication = BasicAuthentication() authorization = DjangoAuthorization() Then I added a new user using Django admin. He's listed as active and staff. No other permissions have been given. Now whey I try the resource URL, it asks for credentials. When I use the new users credentials, I get nothing: {"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 0}, "objects": []} No objects, nothing. If I login as root, I see all the data. How do I assign stuff to the user so it can see the resources? -
Why is PasswordResetView email not being sent
I've followed a guide on using django.contrib.auth.views to reset passwords in the case that a user has forgotten their original password. The views I've set up do not send an email, I do not understand where I've gone wrong in my set up, I believe I've followed the guide as closely as possible. Here is my set up, side by side, my urls.py and settings.py : And Here is the typical result of "sending the email" : Please help me with my misunderstanding, as I assume this process ought to be very straight forward. From the django documentation, PasswordResetView doesn't seem to require any fields which I've not included in order to send the email. -
Django - Using the Django ORM and related managers
The idea is that Requisitions can have multiple lines which is why I included the unique_together contraint on parent_req and sequence. Each line has a status associated with it. I added a rating to each status ranging from 1-5 but there may be some status' with the same rate. The idea is I would like to save the status with the highest rating out of all the lines and pass it to the template. I have tried using .annotate to get the max rating but then I have no way of grabing the actual status field that is tied to that rating. If multiple status' exist for a rating then it should grab the first one it sees. ex. **Status** | **Rating** status1 | 1 status2 | 2 status3 | 3 status4 | 3 status5 | 4 status6 | 5 Modals.py class Requisition(models.Model): username = models.ForeignKey( 'users.CustomUser', on_delete=models.CASCADE, related_name='req_user') signature = models.CharField(max_length=10, blank=True, null=True) class RequisitionLine(models.Model): parent_req = models.ForeignKey('Requisition', on_delete=models.CASCADE, related_name='par_req_line' ) sequence = models.PositiveIntegerField() status = models.ForeignKey('RequisitionStatus', related_name='req_status', on_delete=models.CASCADE, blank=True, null=True) class Meta: unique_together = ('parent_req','sequence') class RequisitionStatus(models.Model): status = models.CharField(max_length=20) rating = models.SmallIntegerField() def __str__(self): return self.status Views.py def pending_action(request): requisition_status = ['All', 'Created', 'For Assistance', 'Assistance Complete', … -
Django form input field not rendering
I followed the Django tutorial on forms and the input fields of the forms do not render on the webpage. I followed https://docs.djangoproject.com/en/2.1/topics/forms/ My forms.py: from django import forms # Create your forms here. class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) My views.py: from django.shortcuts import render from Tienda.forms import NameForm from django.http import HttpResponseRedirect # Create your views here. def index(request): return render (request, "Tienda/home.html") def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form}) And the part of the code that renders it is: <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> Yet the button shows, but the input field don´t. Also, there are no errors on the console.