Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update code whilst a website is live?
Sorry if this is a stupid question but how do I update a live website? I've got a Django (social media) website than I'm about to launch on DigitalOcean but how do I update the code without disrupting the user experience? -
django rest_framework permission error
I'm using dry-rest-permission package to write authentication for django webService. When I write permission method as same as the package docs I encounter internal server error and this :'bool' object is not callable And this is my method: @staticmethod @authenticated_users def has_create_permission(request): return True -
what mean "self" in rest django
enter image description here def get(self, request, format=None): usernames = [user.username for user in User.objects.all()] return Response(usernames) -
Django: Order query by AVG() field in related table
I have two models class Item(VoteModel, models.Model): **some_fields** class ItemRating(models.Model): score = models.IntegerField(default=0) item_id = models.ForeignKey(Item) I want to order Item query by Averadge score from ItemRating In SQL, it will something like this SELECT AVG(ir.score) as rating FROM Item it, ItemRating ir WHERE it.id = ir.item_id ORDER BY rating; How to do it in django ? Thank You! -
Creating charts - best practice
I am preparing a tool to parse and display data on charts. I am using python ( django ) as a backend and HTML5/JS as a frontend. I would like to ask you about best practice: looking at desktop applications ,like tableau, those apps are pulling and saving data internally ( in order to avoid executing many requests ). What are your suggestions, if user open my page the app should save result in the browser memory ( local storage (?) ) or should execute new request after every change in menu ? Thanks in advance, -
Django-floppyforms - validation and sending do not work
I have problem with django-floppyforms. On the page, the form appears as it should - it is a dedicated front-end. However, the validation and sending of the form does not work. I do not know why. My form with django-floppyforms: from events import models import floppyforms.__future__ as forms class ParticipantForm(forms.ModelForm): class Meta: model = models.Participant fields = ('event', 'first_name', 'last_name', 'company', 'street', 'post_code', 'city', 'email', 'phone_number',) widgets = {'event': forms.HiddenInput} Here is my form on register template: <form id="anmelde-form" class="form-default" action="" method="post">{% csrf_token %} {% form form using "floppyforms/event_detail.html" %} <input type="submit" value="{% blocktrans %}Anmelden{% endblocktrans %}" class="btn btn-default bg-mid-gray" /> </form> Here is templete included on register template floppyforms/event_detail.html: {% load floppyforms %}{% block formconfig %}{% formconfig row using "floppyforms/rows/p.html" %}{% endblock %} {% form form using %} <div class="form-input"> <label for="prename">First name*</label> {% formfield form.first_name %} </div> <div class="form-input"> <label for="surname">Last name*</label> {% formfield form.last_name %} </div> <div class="form-input"> <label for="company">Company</label> {% formfield form.company %} </div> <div class="form-input"> <label for="street">Street</label> {% formfield form.street %} </div> <div class="form-input-wrapper"> <div class="form-input small-4 columns"> <label for="area-code">Post code</label> {% formfield form.post_code %} </div> <div class="form-input small-8 columns"> <label for="city">City</label> {% formfield form.city %} </div> </div> <div class="form-input"> <label for="mail">E-Mail*</label> {% formfield form.email … -
Trying to extend AbstractUser to create multiple user types in Django
So I have been searching all around the internet for a full example of how to user AbstractUser when u have at least 2 different models. Didn't find anything conclusive.. at least that would work on latest version of Django (2.0.1). I have 2 models, teacher and student, and registration needs to be different. Besides username, email, name and surname, I need for example, for the student, to upload a profile picture, email, phone, student_ID. And for teacher, bio, academic title and website. Did I start good ? What is the right approach ? class Profile(AbstractUser): photo = models.ImageField(upload_to='students_images') email = models.EmailField() phone = models.CharField(max_length=15, ) class Student(Profile): student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) def __str__(self): return self.name class Teacher(Profile): academic_title = models.CharField(max_length=30) bio = models.TextField() website = models.URLField(help_text="E.g.: https://www.example.com", blank=True) -
Library of Django filters
I have created some Django template filters that I constantly need. I wanted to create a simple library to leverage them, but not sure what'd be the best way to import that. Sample views.py code: from django.template.defaulttags import register @register.filter def get_item(dictionary, key): return dictionary.get(key, '') How can I split this function get_item to a say library.py file and still be able to register the templates only when this library is imported? Thank you! Limitiations: only module-level imports; no wildcards or symbols import. -
django - select2 minimum project
My problem looks like this: I want to use select2 in django. I downloaded and installed the package using the guides provided here : https://github.com/applegrew/django-select2 . But the problem is, that i really don't get this example in /tests. Does anyone has some basic, minimum django project with just 1 field of heavyselect2? Let's assume that I have my project set and one app in that project added. I appreciate any help;) -
ModuleNotFoundError: No module named 'importlib.util'
I was trying to install "importlib.util" using pip: pip install importlib But cmd throws the ModuleNotFoundError: No module named 'importlib.util' here is the error image click me -
Creating a multiple choice form for each primary key in model with Django
I am trying to create a class registration app in Django. To simplify my problem, I have a model for students, blocks (time periods), and classes (lessons). There are multiple classes for each block, and students must register in exactly 1 class for each block. There will be some customization allowed, so it is not known in advance how many blocks there are or which classes are available for each block. I want to generate a form with radio buttons that looks like this: Block A (9:00 - 11:00) Django class for beginners Some other class Yet another class Block B (11:00 - 13:00) Class for something How to math Placeholder class ... Block E (16:00 - 17:30) Choice 1 Choice 2 Choice 3 Choice 4 Currently, my models look something like this: class Student(models.Model): first_name = models.CharField() [...] class Block(models.Model): block = models.CharField( primary_key=True, choices=(('A', 'Block A'), ('B', 'Block B'), ('C', 'Block C'), ('D', 'Block D'), ('E', 'Block E'))) start_time = models.DateTimeField() [...] class Class(models.Model): title = models.CharField() block = models.ForeignKey('Block') [...] So far, I have something like this in my forms.py: class ClassForm(Form): class_choice = ModelChoiceField( queryset=Class.objects.all(), widget=RadioSelect, empty_label=None) And I can serve that form in my views.py, … -
get decimal input in django_filters.FilterSet
how will filter decimal value using django-filter. I need to input decimal value using the filter form. height_lesser = django_filters.NumberFilter(name='height',lookup_expr='lte', widget=forms.NumberInput(attrs={'class': 'form-control'})) I need to change the widget to DecimalInput but it is not supported. In the model i have used DecimalField. -
How to create a docx file using django framework for begginers?
Hi everyone I want to create a docx file using django. I have already installed python-docx on my laptop, I used this command pip install python-docx and I even created a .docx file on my desktop but I do not how to use this on my django project. First of all, do I need modify settings.py from my project in order to import python-docx to django? by the way I want to create these files when someone visit my urls app I have an app called 'planeaciones' and these are my main files: views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'planeaciones/index.html') urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] index template {% extends 'base.html' %} {% block title %}Planeaciones{% endblock %} {% block content %} <h3 class="text-center">Mis planeaciones</h3> <p></p> {% if user.is_superuser %} <p>Hola Administrador</p> {% endif %} {% endblock %} -
Django ImageField in RestFramework
I'm new at Django. my project is in DjangoRestFramework This project has a user: models.py: class Users(models.Model): name = models.CharField(max_length=20, null=True) lastName = models.CharField(max_length=50, null=True) phone = models.IntegerField(unique=True, null=False, default='phone') password = models.CharField(max_length=25, null=True) natNum = models.IntegerField(unique=True, null=True) degImage = models.ImageField(upload_to='Images/degrees/', null=False, blank=False,default='Images/degrees/None/no-img.jpg') natImage = models.ImageField(upload_to='Images/nationalCards/', null=False, blank=False,default='Images/nationalCards/None/no-img.jpg') sex = models.CharField(null=True, max_length=1) province = models.CharField(null=True, max_length=20) city = models.CharField(null=True, max_length=40) job = models.CharField(null=True, max_length=20) code = models.CharField(max_length=4, null=True) last_seen = models.DateTimeField(default=django.utils.timezone.now) points = models.IntegerField(null=False, default=0) scorers = models.IntegerField(null=False, default=0) and in views.py I made a function for registeration but for degImage and natImage there is a problem. views.py @api_view(["POST"]) @parser_classes((MultiPartParser, JSONParser)) def register(request): user_data = request.data if user_data: serializer = UserSerializers(data=user_data) if serializer.is_valid(): phone_number = serializer.validated_data["phone"] try: found_user = Users.objects.get(phone=phone_number) except Users.DoesNotExist: found_user = None if found_user: return Response({ "code": 211, "status": "successfull", "message": "user already exists, try to login" }) else: destination = serializer.validated_data['phone'] message = str(random.randint(1000, 9999)) url = "https://panel.asanak.ir/webservice/v1rest/sendsms/?Username=0216463&Password=123456&Source=02100064636463&Destination={}&message={}" url = url.format(destination, message) r = requests.get(url) r.json() registerInfo = { 'name': serializer.validated_data['name'], 'lastName': serializer.validated_data['lastName'], 'phone': serializer.validated_data['phone'], 'natNum': serializer.validated_data['natNum'], 'password': serializer.validated_data['password'], 'degImage': serializer.validated_data['degImage'], 'natImage': serializer.validated_data['natImage'], 'sex': "", 'province': "", 'city': "", 'job': "", 'code': message } serializer.save(registerInfo) return Response({ "code": 200, "status": "successfull", "message": "code was sent try … -
python website for highlights generation
Hi Actually I am working on a python website cricket video highlights generator in which user will upload cricket match and as an output he will get the highlights but I am totally stuck and I dont know from where to start which libraries to use I'll be thankfull if anybody can help -
Django static css not loaded?
So my app has the following structure: base.html, which contains the nav and the links to the stylesheets and the home.html file, which loads the nav via extends. However, i can't really modify the css inside my home.html file, any suggestions whats wrong? base.html: {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>App</title> <link rel="shortcut icon" href="{% static 'img/favicon.png' %}"> <link rel="stylesheet" href="{% static 'css/app.css' %}"> ...## navbar etc. <div id="body"> <div class="container"> {% block page %} {% endblock %} </div> </div> home.html: {% extends 'base.html' %} {% load staticfiles %} {% block page %} <div class="row"> <div class="col-md-12"> <img src="{% static 'img/banner.gif'%}" class="banner"> </div> {% endblock %} As you can see in the base.html file, i load the app.css file via static method. However, changing for example the banner class in the home.html isn't working at all: #body .banner { width: 100%; margin-bottom: 150px; } No errors in the terminal / console. The app.css file works for the base.html by the way. -
Django application how to use tls1.2 to connect sql server
Using pymssql to connect sql server without TLS1.2 now. But how can I use TLS1.2 to connect sql server?Is there any way to use TLS1.2 to connect sql server in Django Project? Thanks in advance for you inputs. -
Loading form from URL in Bootstrap 3 (Django)
I have a form in a url. I want to load it in an existing page. I'm following this tutorial https://www.abidibo.net/blog/2014/05/26/how-implement-modal-popup-django-forms-bootstrap/ This is the form template {% load i18n widget_tweaks %} <div class="modal-dialog modal-lg" role="document"> <form action="{% url 'flag_post' %}" method="post" id="flag-form" class="form">{% csrf_token %} <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Report Post</h4> </div> <div class="modal-body"> {{ form.media }} {% render_field form.reason class="form-control" %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input type="submit" class="btn btn-primary" value="Save changes" /> </div> </div><!-- /.modal-content --> </form> </div><!-- /.modal-dialog --> <script> var form_options = { target: '#modal', success: function(response) {} }; $('#flag-form').ajaxForm(form_options); </script> This is my link that is supposed to load the form <a class="fa fa-pencil" data-toggle="modal" href="{% url 'flag_post' node.uid %}" data-target="#modal" title="edit item" data-tooltip></a> | I have the following script tag embedded <script src="http://malsup.github.com/jquery.form.js"></script> When I call the url directly the form is displayed, but when I try clicking the button form is not loaded. What is wrong with my code? Is this the right way to load a form from an external URL? -
ImportError Exception Value: No module named urls Exception Location: /home/pradeep/.local/lib/python2.7/site-packages/rest_framework/routers.py
https://tests4geeks.com/django-rest-framework-tutorial/ Above Tutorial URL I am following for djangorestframework API implementatuion My admin site is working perfectly, I can add Student and Universities successfully and after that while I moved to "Django REST framework-based api" steps I did same as given still getting error Can anybody suggest what to do for fix. -
Users are not being authenticated after login
This is my first time working with Django and I'm trying to create a simple login page. I would like the login page to be located at the base URL (index) of the site and then redirect to "assignments/" with "assignments/" and all other pages on the site only being accessible if the user is logged in. When I try to view if the user is authenticated (using "request.user.is_authenticated"), the view handles the user as if he/she is not logged in. views.py from django.contrib.auth import login as dj_login def login(request): return render(request, 'mainapp/login.html') def assignments(request): if request.user.is_authenticated: assignment_list = Assignment.objects.all() context_dict = {'assignments': assignment_list} return render(request, 'mainapp/assignments.html', context_dict) else: return HttpResponse("You must login first") def show_assignment(request, assignment_name_slug): try: context_dict = {} assignment = Assignment.objects.get(slug=assignment_name_slug) context_dict['assignment'] = assignment except Category.DoesNotExist: context_dict['assignment'] = None return render(request, 'mainapp/projectpage.html', context_dict) def user_login(request): information. if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: dj_login(request, user) return HttpResponseRedirect(reverse('assignments')) else: return HttpResponse("Your account is disabled.") else: print("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied.") else: return HttpResponse("You must login first") application urls.py urlpatterns = [ url(r'^$', views.assignments, name='assignments'), url(r'^(?P<assignment_name_slug>[\w\-]+)/$', views.show_assignment, name='show_assignment') ] project urls.py urlpatterns … -
NoReverseMatch django Reverse for 'profilepk' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/profile/(?P<pk>\\d+)/$']
NoReverseMatch at /home/ this is error m not able to solve this pop on screen account/profile/(?P\d+)/$' is there any error in below code viwes.py,urls.py,models.py Error during template rendering In template C:\Users\shubham\Desktop\app1\account\templates\basic.html, error at line 24 Reverse for 'profilepk' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/profile/(?P\d+)/$'] urls.py from django.conf.urls import url from home import views app_name = 'home' urlpatterns = [ url(r'^$', views.home.as_view(), name='home'), url(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.Create, name='create') ] views.py from django.contrib.auth.models import User from django.shortcuts import render, HttpResponse, redirect from django.views.generic import TemplateView from home.forms import RegiForm from home.models import Datastrore, Friendlist class home(TemplateView): template_name = 'home/home.html' def get(self, request): forms = RegiForm() datastore = Datastrore.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friendlist.objects.get(current_user=request.user) friends = friend.user.all() args = {'form': forms, 'post': datastore, 'user': users,'friend': friends} return render(request, self.template_name, args) def post(self, request): froms = RegiForm(request.POST) if froms.is_valid(): post = froms.save(commit=False) post.user = request.user froms.save() text = froms.cleaned_data['post'] args = {'form': froms, 'text': text} return render(request, self.template_name, args) def Create(request, operation, pk): friends = User.objects.get(pk=pk) if operation == 'add': Friendlist.Create_list(request.user, friends) elif operation == 'remove': Friendlist.Remove_list(request.user, friends) return redirect('home:home') models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Datastrore(models.Model): post = models.CharField(max_length=100) user … -
Error Incorrect type. Expected URL string, received dict
I am using volley to post data to django server.This is the format I need to Post the data { "no_people": 9, "entry_time": "2018-01-02T15:00:00Z", "predicated_time": "2018-01-02T16:00:00Z", "status": "W", "foodie": "http://localhost:9500/api/users/99/" } The foodie field consist of URL. When I am sending post request I am getting error as POST /api/restqueue/ - 400 {'content-type': ('Content-Type', 'application/json'), 'allow': ('Allow', 'GET, POST, HEAD, OPTIONS'), 'vary': ('Vary', 'Accept')} b'{"foodie":["Incorrect type. Expected URL string, received dict."]}' [23/Jan/2018 05:15:41] "POST /api/restqueue/ HTTP/1.1" 400 66 How to resolve this and send Post Request? -
how do I get that entire object instead of the foreign key. please see below code and output so you can understand
my question is how do I get that entire object instead of the foreign key. please see below code and output so you can understand my question These are my models.py class Professor(models.Model): professor_id = models.AutoField(primary_key=True, auto_created=True) name = models.CharField(max_length=256) email = models.CharField(max_length=256) mobile = models.CharField(max_length=256) created_at = models.DateTimeField() updated_at = models.DateTimeField() class Preference(models.Model): preference_id = models.AutoField(primary_key=True, auto_created=True) professor = models.ForeignKey('Professor', on_delete=models.CASCADE) rank = models.IntegerField() created_at = models.DateTimeField() updated_at = models.DateTimeField() These are my views.py class CreateListMixin: def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) class PreferenceViewSet(CreateListMixin, viewsets.ModelViewSet): queryset = Preference.objects.all() serializer_class = PreferenceSerializer This is my serializers.py class PreferenceSerializer(serializers.ModelSerializer): class Meta: model = Preference I'm getting the output as [ { "preference_id": 1, "rank": 1, "professor": Eshwar "created_at": "2018-01-13T00:00:00Z", "updated_at": "2018-01-13T00:00:00Z" } ] what to do if I have to get professor details as object: [ { "preference_id": 1, "rank": 1, "professor": { professor_id = 1 name = Eshwar email = .... mobile = .... created_at = ... updated_at = .... } "created_at": "2018-01-13T00:00:00Z", "updated_at": "2018-01-13T00:00:00Z" } ] my question is how do I get that entire object instead of foreign key Any help is appreciated. -
Obtain the display value of a choice Field from a function within the own model
I have a method inside a model class, and I want to get the display value of a choice field in such model, but I get a weird value. This is the code: class Actor(models.Model): PERSON = '0' ROLE = '1' AUTO = '2' TYPE_CHOICES = ( (PERSON, 'Person'), (ROLE, 'Role'), (AUTO, 'Auto'), ) alias = models.CharField(max_length=10, default='', unique=True) name = models.CharField(max_length=255, default='') email = models.EmailField(null=True, blank=True) actor_type = models.CharField(max_length=1, choices=TYPE_CHOICES, default=PERSON) long_description = models.TextField(max_length=long_description_max_length, default='', null=True, blank=True) def get_list_fields(self): list_fields = { 'id' : self.id, 'name' : self.alias, 'description' : self.name, 'extra_fields' : "[{}][{}]".format( self.email, getattr(self, 'get_actor_type_display') ) } return list_fields And this is the result i get: {'id': 1, 'name': 'hugo', 'description': 'Hugo Luis Villalobos Canto', 'extra_fields': '[hugo@utopia-software.net][functools.partial(>, field=)]' } I don't know what that functools.partial(>, field=)stands for, and I don't know how to get the result I want: the display value of the current content of the field. Thanks for your help. -
I cannot get my PIP 9.0.1 to work properly
I'm working with a Hostgator Shared package to install and run my Django projects, I followed all the steps from here http://support.hostgator.com/articles/django-with-fastcgi#shared-reseller (section: Setup Django Using Virtualenv) I get stuck in step 3 (Install Django): ~/mydjango/bin/pip install django I get this output: Exception: Traceback (most recent call last): File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/commands/install.py", line 272, in run with self._build_session(options) as session: File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 93, in user_agent from pip._vendor import distro File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 1050, in <module> _distro = LinuxDistribution() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 594, in __init__ if include_lsb else {} File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 933, in _get_lsb_release_info raise subprocess.CalledProcessError(code, cmd, stdout) CalledProcessError: Command 'lsb_release -a' returned non-zero exit status 3 Traceback (most recent call last): File "/home2/belldentjc/mydjango/bin/pip", line 11, in <module> sys.exit(main()) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as session: File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 93, in user_agent from pip._vendor import …