Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a new record from django query set
I have heard of a django orm hack somewhere. It goes like this dp = SomeModel.objects.filter(type="customer").last() dp.id = dp.id + 1 #changing id to a new one dp.save() The last step supposedly creates a new record provided the value of id being used doesn't exist. In case the incremented id exists, then the save method acts like the update method. example :: dp.version += 1 #updating some random field dp.save() # will change the newer version of dp.id I would like to ask veterans in django two questions for our benefit, Is there a sure shot way of creating a new record from an old record with the latest auto_increment_pk instead of pk + 1 method Is the above method any faster or better. One advantage I see is if I have a model with 10 fields and I want to create a new record from an old one with only 1 or 2 changes from the older one, this method saves 8 lines of code. Thank You -
Deleting objects that are not referenced by other objects
I have a need to cleanup my database, hence looking for an efficient way to DELETE all objects that are not referenced by other objects via the ForeignKey. Currently, I am doing the following: from django.db import transaction from django.contrib.admin.utils import NestedObjects from django.db import DEFAULT_DB_ALIAS from django.db.models.deletion import Collector from mygeo.models import Location locations = Location.objects.filter(office__slug='bb-co') with transaction.atomic(): for location in locations.iterator(): collector = NestedObjects(using=DEFAULT_DB_ALIAS) # database name collector.collect([location]) # list of related objects that will be deleted objects_to_delete = collector.nested() if len(objects_to_delete) == 1: location.delete() The above works well but takes a longer time to process, since I have over 100000 records to query. Is there a better way than the above to achieve this? -
How to filter the query_set by multi-params?
How to filter the query_set by multi-params? class UserListAPIView(ListAPIView): """ return the user list """ pagination_class = UserPageNumberPagination class Meta: ordering = ['-id'] def get_serializer_class(self): return UserListSerializer def get_queryset(self): username = self.request.query_params.get("username") real_name = self.request.query_params.get("real_name") phone = self.request.query_params.get("phone") company_name = self.request.query_params.get("company_name") return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False, username=username, real_name=real_name, phone=phone, company_name=company_name ) # if `username, real_name, phone, company_name` all are None, there gets `[]` The serializer: class UserListSerializer(ModelSerializer): """ user list serializer """ username = serializers.CharField(allow_null=True, allow_blank=True) real_name = serializers.CharField(allow_null=True, allow_blank=True) phone = serializers.CharField(allow_null=True, allow_blank=True) company_name = serializers.CharField(allow_null=True, allow_blank=True) You see, my username , real_name, phone, company_name all are allow_null. I want to query all the user that meet the conditions. But gets [], when I do not pass the username, real_name, phone, company_name. I want to if the username is None, it do not filter the username, if real_name is None, it do not filter the real_name. (I means it do not filter out it) I have a idea, but it is fit for less fields, if there is only one username field: def get_queryset(self): username = self.request.query_params.get("username") if username == None or username == '': return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False) else: return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False, username=username) But there … -
Djando DRF nested items
I'm tryng to create a set of objects from a POST request,in this I send the pk list of the objects that should be created: data = { 'a_ref':["17629","17630","17631"] } x= Model_Serializer(data=data) this are my serializers: class A_Serializer(serializers.ModelSerializer): class Meta: model = A fields = ('pk',) class Model_Serializer(serializers.ModelSerializer): a_ref = A_Serializer( many=True) def create(self, validated_data): tracks_data = validated_data.pop('a_ref') model = Model.objects.create(**validated_data) for track_data in tracks_data: A.objects.create(ref=model, **track_data) return model class Meta: model = models.Model but I get this: [14]: x.is_valid() Out[14]: False x.errors Out[16]: ReturnDict([ ('a_ref', [{'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}, {'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}, {'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}])]) -
Not able to set up python environment to run python script for webapplication
Hi Pleaes help me to setup a python environment on my window 7 machine to run python script for web application. I have full script but not able to run it on localhost server as it is running on production server with a domain name. Please Help! -
python Django TinyMCE
I'm trying to add an in-page editor to a project and I came across TinyMCE a HTML editor. I've been following the tutorial on how to integrate it into my app but have been getting very confused. How to set plug-ins and edit font and stuff still remain a mystery. I'm a novice in Django so any ideas will be helpful -
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.