Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ChoiceField with RadioSelect does not automatically select None values
I am loading a form to edit a model defining the following field: CHOICES = ((1, 'One'), (2, 'Two'), (None, 'Nothing')) choice = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) The problem is that when the initial value for choice is None, it doesn't get automatically selected in the form. What can I do about it? -
How do I pass arguments in Django REST framework modelviews?
Here is my views for DRF API class CityEventsViewSet(viewsets.ModelViewSet): def __init__(self, request, *args, **kwargs): queryset = CityEvents.objects.filter(city=kwargs.get('city_name')) serializer_class = CityEventsSerializer URL: router.register(r'cityevents/(?P<city_name>[\w\-]+)/$', CityEventsViewSet, base_name='cityevents') I am not able to access the views function. It is not able to resolve the URL. -
Djnago - Instance Value
In this u_form and p_form im getting the current user which is logged in and when i am updating another users it is filling up form with logged in user instant i want userprofile detail of the user i want. So basically i want to change instance request.user and request.user.userprofile will have current user. But i want to update the user which is not logged in. I want a this request.user from template so that i can update it. u_form = UserUpdateForm(instance=request.user) p_form = UserProfileForm(instance=request.user.userprofile) -
Overriding the UserDetailsSerializer in django-rest-auth
I am trying to modify the UserDetailsSerializer with a customized User Detail, but when the server is running, it throws an error of " 'User' object has no attribute 'user'". I tried a lot of methods and none of them work. My code is: mode.py class userProfileModel(models.Model): GENDER = [ ('', ""), ('M', "Male"), ('F', "Female") ] user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE, default='') age = models.DateField(auto_now_add=True) gender = models.CharField(max_length=10, choices=GENDER, default='') phone = models.IntegerField(default=0) user_is_active = models.BooleanField(default=False) def __str__(self): return self.user.username And serializers.py from rest_auth.serializers import UserDetailsSerializer from rest_framework import serializers from .models import userProfileModel class Profile(serializers.ModelSerializer): user = UserDetailsSerializer() class Meta: model = userProfileModel fields = ('user',) class UserDetailsSerializer(UserDetailsSerializer): profile = Profile(many=True) class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('profile',) read_only_fields = ('',) And settings.py REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER': 'app.serializers.UserDetailsSerializer', } When I run this code, it throws this error. Got AttributeError when attempting to get a value for field profile on serializer UserDetailsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'profile'. -
Additional views to Django Rest Framework ViewSet
I've got simple DRF ViewSet for a model, located at /gen_req/ class GenerationRequestViewSet(viewsets.ModelViewSet): queryset = GenerationRequest.objects serializer_class = GenerationRequestSerializer It has default POST/GET/etc. handlers. However, I want to add another one for GET as well for different url patter (/gen_req/created_list: class GenerationRequestViewSet(viewsets.ModelViewSet): queryset = GenerationRequest.objects serializer_class = GenerationRequestSerializer @action(methods=['get']) def special_get_handler(self, request): queryset = GenerationRequest.filter(...) # Some extra filtering here serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Is there a way to create such view within the ViewSet or another APIView should be created? -
How to fix "__init__() takes 1 positional argument but 2 were given" error in Django
TypeError at /accounts/login/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 2.1.4 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Projects\virtu\lib\site-packages\django\core\handlers\base.py in _get_response, line 124 -
Django - The page don't load after click
i'm new in Django developing. I'm following the tutorial about Library on MDN (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django) Until i follow the code all work but i'm trying implement author page by myself. Probably is very stupid issue but is one day that i'm turning around like a dog with its tail. There is 2 page: author_list and author detail. I set urls.py(in my project) i set view.py and crate my template. I follow the same step of tutorial for realize book_list and book_detail but when i click on my author the page don't go to the detail of that author and stay in author_list.html. Here the code urls.py : path('authors/', views.AuthorListView.as_view(), name='authors'), path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'), Here views.py: class AuthorListView(generic.ListView): model = Author class AuthorDetailView(generic.ListView): model = Author Here author_list.html with link get_absolute_url: {% extends "base_generic.html"%} {% block content %} <h1>Author list</h1> {% if author_list %} <ul> {% for aut in author_list %} <li><a href="{{ aut.get_absolute_url }}">{{ aut.first_name }} - {{ aut.last_name }}</a></li> {% endfor %} </ul> {% else %} <p>There are no author.</p> {% endif %} {% endblock %} Here author_detail.html: {% extends "base_generic.html" %} {% block content %} <h1>Author</h1> {% if author %} <p><strong>Nome: </strong> {{ author }}</p> <p><strong>Nato il : </strong> … -
how can i show model information inside another model? in django
So i have three models , and there are connected with foreing key. i am using list_display on "avaria" , and i want to show the name of the "pavimento" inside of the model "avaria". What is the best options to that? class pavimento(models.Model): pavimento_nome = models.CharField("Pavimento",max_length=200) class avaria(models.Model): avaria_consumidores = models.IntegerField(blank=True,null=True,verbose_name="Consumidores") class pavimentacao(models.Model): pavimentacao_id=models.ForeignKey(avaria,related_name='avariaObjects',on_delete=models.CASCADE) pavimentacao_avaria = models.ForeignKey(pavimento,on_delete=models.CASCADE, verbose_name="Pavimento") -
Custom lookup, parameter contains a field value
I have a Model named Item, containing a field named tag, so I want to find if given a string value like "hello world", if any of the Item model object tag field is contained in the value, like if field tag value is "hello" or "world" it should match. I have written a custom lookup for it, but how to use the "%" value in the SQL query @Field.register_lookup class PartOf(Lookup): lookup_name = 'partof' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return "{} LIKE {}".format(rhs, lhs), params This matches the exact fields, currently it is like PATTERN but I want this %PATTERN% -
Django Login system for the twofa with Google auth and twilio
How can i setup the login system for the 2Fa using multiple either google authenticator or twilio in django Problem is when user signup it will select the twofa type at signup and at every we have to force user to enter otp after the login if it succeeds then we need to show dashboard -
how to find a localhost using a django server to contact with android device?
I've set up a django server on ubuntu and I want to get json data from it and show them on android device but I don't know the server name. I tried 10.0.2.2, localhost, 127.0.0.1 and ip address but none of them worked. like: Thread thread = new Thread(new Runnable() { @Override public void run() { HttpClient httpClient = new DefaultHttpClient(); HttpGet method = new HttpGet("http://localhost:8000/books/4/?format=json"); try { HttpResponse response = httpClient.execute(method); InputStream is = response.getEntity().getContent(); content[0] = IStoString(is); Log.i("SERVERTEST", content[0]); } catch (ClientProtocolException r) { r.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); thread.start(); code works with other APIs. The Exception is: connection to http://127.0.0.1:8000 refused -
create an item carousel for my suggested product list on homepage
I want to create an item carousel for my suggested product list on homepage, I'll try a lot but it can't be work. This suggested product list generated by for loop. I mention the code below, Please help me. Thank you. <div class="row"> <div class="col-md-4"> <div class="carousel slide" id="myCarousel" data-ride="carousel"> <ol class="carousel-indicators"> <li class="active" data-slide-to="0" data-target="#myCarousel"></li> <li class="active" data-slide-to="1" data-target="#myCarousel"></li> <li class="active" data-slide-to="2" data-target="#myCarousel"></li> </ol> <div class="carousel-inner" id="caro1"> {% for instance in product_list %} <div class="item {% if forloop.counter == 1 %}active{% endif %}" id="slide{{ forloop.counter }}"> {% if instance|get_thumbnail:"micro" %} <a href='{{ instance.get_absolute_url }}'> <img src='{{ instance|get_thumbnail:"micro" }}' width="50" height="50"/> </a> {% endif %} <br/> <div class="carousel-caption"> <a href='{{ instance.get_absolute_url }}' style="font-size:20px;color:white"> {{ instance.title }} </a> <br/> <div style="font-size:20px;color:white"> {{ instance.get_html_price|safe }} </div> </div> </div> {% endfor %} </div> <a class="left carousel-control" data-slide="prev" href="#myCarousel"><span class="icon-prev"></span></a> <a class="right carousel-control" data-slide="next" href="#myCarousel"><span class="icon-next"></span></a> </div> </div> -
Data validations on model - Time/Date clash
I am learning Django and I am building a cinema booking system with it. In this cinema booking there is only one cinema. Each cinema has one room only. In this room, a movie is projected each hour. This cinema has only one employee and several customers. I set the employee as a superuser so he can add/delete etc. a movie from '/admin'. Therefore, I have only two models. First, Accounts (aka costumers). Secondly, Movie. I want to allow the creation of a new movie only IF: - The date of creation of the movie is past now (it cannot be created for a past time). - Since there is only a room, a movie can be created only if in that specific date (day-month-year hour-minute-second) there is not already a movie. My Movie model is: class Movie(models.Model): title = models.CharField(max_length=255) description = models.TextField(null=True) price = IntegerField(default=10) movie_duration = models.IntegerField(default=1), when_movie_created = models.DateTimeField() when_movie_displayed = models.DateTimeField() who_created = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False) The outcome that I want is the following: if the employee (aka superuser) adds a new movie BUT either he adds it in the past OR he adds with a date that clashes with an already existing movie, … -
Getting django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module, while trying to perform the first migration
I am setting up a Django backend for my application. I am trying to change the default sqlite database to mysql. While performing the first migration, I get the following error: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/init.py", line 357, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in class AbstractBaseUser(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 101, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 305, in add_to_class value.contribute_to_class(cls, name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/options.py", line 203, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/init.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 202, in getitem backend = load_backend(db['ENGINE']) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/init.py", line … -
Django send mail using EmailMultiAlternatives -Invalid block tag on line 2: 'IFEQUAL'
I am trying to send mail in djnago using EmailMultiAlternatives but getting error in django template tag in .txt file here my email.html file something look like this <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for i in mylist%} {ifequal i 1} GO {% else%} Come {% endifequal %} {% endfor%} </body> </html> email.txt file {% for i in mylist%} {ifequal i 1} GO {% else%} Come {% endifequal %} {% endfor%} code plaintext = get_template('email.txt') htmly = get_template('email.html') d = {"mylist" :[1,2,3,4,5]} text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives('subject', text_content, settings.from_email, ['test@test.com']) msg.attach_alternative(html_content, "text/html") msg.send() here i am getting error that "Invalid block tag on line 2: 'IFEQUAL', expected 'empty' or 'endfor'. Did you forget to register or load this tag?" here when i remove ifequal tag from email.txt it's working fine. how can i add conditions inside for loop in .txt file or any alternative solution for send mail in this situation. -
Trouble understanding how the Django save() handles *args
Was fighting yesterday with the issue of importing pics from URL to the Django model. Was able to come up with a working solution, but still don't know how this is works. How a save func knows what kind of *args it could process and in what order? Because when I changed places for picture object and filename it didn't work TypeError: join() argument must be str or bytes, not 'File'. Could not understand it reading the docs - https://docs.djangoproject.com/en/2.1/_modules/django/db/models/base/#Model.save. The script below putting NHL players names, id and profile pics to my Player model. Any help? the commands file: import urllib.request as urllib import requests from django.core.management.base import BaseCommand, CommandError from django.core.files import File from players.models import Player URL_PLAYERS = 'http://www.nhl.com/stats/rest/{}' URL_PICS = 'https://nhl.bamcontent.com/images/headshots/current/168x168/{}.jpg' class Command(BaseCommand): def import_player(self, data): id_ = data["playerId"] content = urllib.urlretrieve(URL_PICS.format(id_)) pic = File(open(content[0], 'rb')) # do I need to close the file here? file = f'{data["playerName"]}.jpg' player = Player(name=data["playerName"], nhl_id=id_) player.save() player.image.save(file, pic) def handle(self, *args, **options): params = {"isAggregate": "false", "reportType": "basic", "isGame": "false", "reportName": "skaterpercentages", "cayenneExp": "gameTypeId=2 and seasonId=20182019"} response = requests.get(url=URL_PLAYERS.format("skaters"), params=params) response.raise_for_status() data = response.json()["data"] for player in data: self.import_player(player) the models file: from django.db import models class Player(models.Model): name … -
Django REST endpoint for list of objects
I have a Django application witch under /api/v1/crm/ticket can create tickets via a POST call. Now I want to be able to send different types of tickets to the same endpoint having a "dynamic" serialiser depending on the data send. The endpoint should select the right "model" depending on the data properties existing. I tried Django db.models but dit not get them to work as I write the tickets to another external system and just pass them through, so no database table is existing and the model lacks the necessary primary key. I would like to also avoid duplicating the data structure in the POJO and the serialiser just using the model with the validation spec. Can you help me out? Code class TicketAPIView(CreateAPIView): serializer_class = TicketSerializer permission_classes = (IsAuthenticated,) class TicketSerializer(serializers.Serializer): title = serializers.CharField(max_length=256) description = serializers.CharField(max_length=2048) type = serializers.ChoiceField(TICKET_TYPES) def create(self, validated_data): if validated_data['type'] == 'normal': ticket = TicketPOJO( validated_data['title'], validated_data['description'], ) ... else: raise Exception('Ticket type not supported') return ticket Files /my-cool-app /apps /crm /api /v1 /serializers serializers.py __init.py urls.py views.py /clients /ticket provider.py /user provider.py /search /config -
Django REST arch design for service usable from endpoint and other app
I have an existing Django REST stack with multiple applications. Now I want to be able to call an action from a) outside using a REST endpoint and b) from another app within the stack. Now I want to for example call the crm service from search but have the same "behaviour" when calling from outside using the view->serialiser way. How can I reuse as much as possible avoiding duplicating code? The stack itself looks something like /my-cool-app /apps /crm /api /v1 /serializers serializers.py __init.py urls.py views.py /clients /ticket provider.py /user provider.py /search /config -
Django -I need to implement drag and drop to upload file
I am using django to develop a small project and i want to implement drag and drop to upload file .I have already implemented basic file upload from choose file and it is working fine . Please help me I have tried below code for simple file uploading but i need drag and drop and i dont know how to implement the same . {% block content %} <div method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"><br><br> <input type="submit" value="upload"> {% endblock %} Views.py def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage(location="test/uploadedmedia") filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'upload.html', {'uploaded_file_url': uploaded_file_url,"fileupload":"File uploaded successfully"}) return render(request, 'upload.html') I need file to be dragged and gets uploaded. -
Django login page
How to Implement Multiple User Types with Django only admin will register all users and user type I want to create Login page only Admin will add, remove, update and delete. user only login and logout on this django app -
Django: why am i getting malloc?
I am new to Django and getting below error in a simple todo app that i trying to create. I am not sure what is causing it. I only added one app of 'todos' and when i go to admin page i get this error below on pycharm. *[21/Dec/2018 06:58:05] "GET /admin/ HTTP/1.1" 200 3042 Python(1756,0x700009e06000) malloc: error for object 0x1015c6ae4: pointer being freed was not allocated set a breakpoint in malloc_error_break to debug Process finished with exit code 134 (interrupted by signal 6: SIGABRT)* -
django dynamic model object in query api
I have 5 model class with geometric data and other different parameters. In a search I need to query the data in all these five model classes based on the user selection i.e. dynamically change model class in query. For that in django 1.4 I used models.dict[layer] and based on the select the layer field varies. But now I am working in django 1.11 and this is not working. what is the best method for the solution. -
Build failed running pavelib.assets.update_assets: Subprocess return code: 1
/bin/cp -rf node_modules/which-country/index.js common/static/common/js/vendor /bin/cp -rf node_modules/sinon/pkg/sinon.js common/static/common/js/vendor /bin/cp -rf node_modules/squirejs/src/Squire.js common/static/common/js/vendor ---> pavelib.assets.webpack python manage.py lms --settings=devstack print_setting STATIC_ROOT 2>/dev/null Build failed running pavelib.assets.update_assets: Subprocess return code: 1 -
Creating sitemap using django
I am trying to get my website to have a webpage with sitemaps so google can index my website more readily. I have been successful already with multiple sitemaps but I cannot get one I am working with to function. Can anyone see my issue here? This is what I believe is the relevant code? I would greatly appreciate any help! Thank you in advance! models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def get_absolute_url(self): return reverse('detail', kwargs={'question_id':self.id }) urls.py: #in my project from django.conf.urls import include, url from django.urls import path from django.contrib.sitemaps.views import sitemap from django.contrib import admin from django.contrib.sitemaps import GenericSitemap admin.autodiscover() import hello.views from polls.models import Question info_dict3 = { 'queryset': Question.objects.all(), } sitemaps3 = {'polls': GenericSitemap(info_dict3, priority=0.6)} urlpatterns = [ path('sitemap3.xml', sitemap, {'sitemaps': sitemaps3}, ... name='django.contrib.sitemaps.views.sitemaps3'), ] views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404, HttpResponseRedirect from .models import Question from django.urls import reverse from django.views import generic def detail_view(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) urls.py: #in my app from django.urls import path from django.contrib.sitemaps.views import sitemap from django.contrib import admin from django.contrib.sitemaps … -
datetime parse shows 31 as incorrect day is out of range
datetime.date(2018,8,31) ipdb> ret= parse('September').date() ValueError: day is out of range for month Pleae help me if you are familiar with this error.