Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am trying to show flights related to the id when u type in the id on the url but it brings up an error (function-object-has-no-attribute-objects)
from django.shortcuts import render from django.http import Http404, HttpResponse from .models import flight Create your views here. def index(request): flights = flight.objects.all() context = { "flights": flight } return render(request,"flights/index.html",context) def flight(request, flight_id): try: flight = flight.objects.get(pk=flight_id) except flight.DoesNotExist: raise Http404("flight does not exist") context = { "flight": flight } return render(request,"flights/flight.html", context) -
How can I import the structure of a docx in python-docx?
I want to build a docx file via python-docx in django. However, this document is based on a pre-existing template, which has several pages, styles and so on. And I have this template only as a docx file. Do I have to compare with the template and give python-docx instructions for every single paragraph and run? Or is it somehow possible to import the structure of a docx file with python-docx? I found examples how to read an existing file, getting all the text and so on. But I did not find instructions how to get the structure of a file and therefore how to rebuild a complex document easily. -
Display username in template with custom user model as welcome message
I want to display username in base.html but it's not working.I am learning django if you see any mistake please tell. # settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', ) User model class accountUser(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] base.html <li><a href="#">{{ accountUser.username }}</a></li> <li><a href="{% url 'account_logout' %}">Logout</a></li> -
how to add a choice field to django user model
I am completely satisfied with the way user model handles the auth, but I want to add a choice field to it that the users could choose between being a patient, doctor or a regular user. then creating the profile model according to their chosen field. for instance the patients have info about their sickness but doctors don't. is there any other way except abstractuser ? because I really don't want to start make another project again from scratch. thank you for the responses this is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) and this is my forms.py: class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] -
Django - Password2 from User Registration Form coming a none in request dict
below is the cleaned data from User registration form and appears password2 is not in the request. Not sure what is the reason. I have included the form and view code below. please assist why password2 is missing. {'username': 'xyzabc', 'first_name': 'xyz', 'last_name': 'abc', 'email': 'xyzabc@gmail.com', 'password1': 'kjfhekwjfhekjf'} forms.py class RegistrationForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'username'}), label="Username") first_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'first_name'}), label="First Name") last_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'last_name'}), label="Last Name") email = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'email'}), label="Email") password1 = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control','type':'password', 'name':'password1'}), label="Password") password2 = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control','type':'password', 'name': 'password2'}), label="Password (again)") class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] def clean(self, *args, **kwargs): cleaned_data = super(RegistrationForm, self).clean() print(cleaned_data) if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError("Passwords don't match. Please try again!") return self.cleaned_data views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from .forms import RegistrationForm def registerPage(request, *args, **kwargs): form = RegistrationForm() register_context = { 'form': form } print(register_context) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return render(request, "register.html", register_context) -
["'02-05-2020' value has an invalid format. It must be in YYYY-MM-DD format."]
I get the above error as I try to enter 02-05-2020 date in the database. I want the format of date entered to be DD-MM-YYYY and not YYYY-MM-DD. I am using DateField. date = models.DateField() -
Django/MySQL LOCK TABLE with transaction.atomic gives savepoint does not exist
I have activities, which can have multiple 'action' holders, where eacht 'action_holder' can have a dynamic role. For example 'gym-leader', 'student', etc. These roles can be create by the client and are not fixed. Also the 'primary' action_holder_role is denormalized on the model, because otherwise the QuerySet filtering would take to long (more then 2000 activities are loaded on one page, if I would use normal cache instead of the database denormalisatie it would take 20+ seconds instead of 2/3 seconds). For simplicity a lot of fields are taken out in the example. Please note it creates a race condition, which is why the LOCK TABLE is necessary. class Activity(models.Model): data = models.DateField() action_holders = models.ManyToManyField(settings.AUTH_USER_MODEL, through='ActivityUserRole', related_name='realactivities') cached_primary_action_holder = models.ForeignKey('ActivityUserRole', null=True, blank=True, on_delete=models.SET_NULL, related_name='activity_primary_action_holder_role') order = models.IntegerField() class ActivityUserRole(models.Model): role = models.ForeignKey('Role', on_delete=models.PROTECT) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) primary = models.BooleanField(default=False) # primary for realactivity class Role(models.Model): name = models.CharField(max_length=255) My problem is that when I create a new activity, I give the new_action_holders as an argument to the activity and call set_new_action_holders to create the corresponding ActivityUserRoles after saving the new activity (because the ActivityUserRole needs the activity, so it should be saved first). The … -
django-graphene mutation of many to many field
CreateArticle(input:{ title: "title", subTitle: "subtitle", imageCaption: "new caoption", publish: false, categoryName: "test", tagName: "test" }) { article{ title subTitle category{ name } } } } this code get error message "Direct assignment to the forward side of a many-to-many set is prohibited. Use tags.set() instead." -
Python Arelle library throwing Permission Error "/home/nagat/"
Created an XBRL parsing python script using Arelle library which works fine locally but when I deployed it on the server, In celery log I'm getting this error saying Permission Error "/home/nagat/" did some research and found an issue on GitHub which refers to this problem (https://github.com/josw123/dart-fss/issues/2) still no luck. -
Best approach to writing a python based app with web frontend and backend tasks
I've been researching and unsuccessfully trying to use Django and Django Background tasks for a webapp I'm writing. This app will be launch as a service on linux and will automatically start background tasks. The web interface will show various pieces of information. Task status etc.., pausing the background tasks etc.. I have the backend running and logging, but now I'm wanting to put the web interface over the top, and I'm not sure on how to do this. I've looked at Django/Background tasks, but can't quite see how they can be used. The background tasks should start automatically without anyone hitting a webpage. Maybe I'm over complicating it using Django, and I should just use threading and run a simple HTTP web server, or create them as two seperate apps. Background Processor <-> Database <-> Web Application (gets data from database) Background Tasks Processing (Start automatically run application is launched using S6 overlay) Web Interface (started when background daemon is launched, display information on background processing) Thanks any help and direction offered. -
using custom signup form in django allauth and rest-auth and modify the serializer
i am trying to use custom user model and a custom sugnup form in django rest-auth and allauth but i cannot modify the django restauth signup/ register form can anyone help with it models.py from django.db import models from django.core.validators import RegexValidator from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from .managers import UserManager phone_number_regex = RegexValidator( regex= "^((\+91|91|0)[\- ]{0,1})?[456789]\d{9}$", message="Please Enter 10/11 digit mobile number or landline as 0<std code><phone number>", code="invalid_mobile", ) USER_CHOICES = [ ("customer","customer"), ("shopkeeper","shopkeeper"), ("rider","rider") ] class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) phone = models.CharField(max_length=14, validators=[phone_number_regex]) user_type = models.CharField(choices=USER_CHOICES,max_length=50) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name','user_type','phone'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name manager.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, password, **extra_fields): """ Creates … -
Django Rest Framework AttributeError: 'Response' object has no attribute 'pk'
After registering a new user I want to return the token along with the user data so I've got the following serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create_token(self, user): token, created = Token.objects.get_or_create(user=user) return token def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() token = self.create_token(user) UserProfile.objects.create(user=user, **profile_data) resp = { 'token': token.key, 'user': user, } return Response(data=resp, status=status.HTTP_200_OK) But it's not working. I'm getting the following error: AttributeError: 'Response' object has no attribute 'pk' I'm new to DRF so I don't know what I'm missing. -
how to use django-emoticons in django 3
i've found on Django-PyPI django-emoticons package i've installed it and did all the things in the settings file i even have {% load static %} in my template and i still have an error like: "django.template.exceptions.TemplateSyntaxError: 'staticfiles' is not a registered tag library." in my {% extends "blog/base.html" %} base template i also have {% load static %}. Are there any other credentials for Django 3 to use this package? settings.py INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'emoticons', ] template {% extends "blog/base.html" %} {% load static %} {% load crispy_forms_tags %} {% load emoticons_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {% emoticons %} {{ form|crispy }} {% endemoticons %} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} -
Send emails to clients email address
I'm wanting to use send_mail() to have messages from the contact form send to my clients email address. I think what I'm missing is the "email backend" in my settings.py, which I don't really understand how to use properly.. Here's my settings.py: settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' -
Django convert imagefield to Foreign key UUID
I have django project in that, i had imagefield like below certificate = models.ImageField(null=True, blank=True, max_length=1000) but i need to change the imagefield to foreign key UUID, like below certificate = models.ForeignKey(Certificates, null=True, blank=True, on_delete=models.CASCADE) but i'm getting migrate error like below, Applying templates.0016_auto_20200502_0452...Traceback (most recent call last): File "/home/sakthips/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for type uuid: "" this error is little weird, can someone help me to resolve. I know i can delete the existing field and add new field that's one solution. I was expecting some other solutions. -
I have pip installed the module in my virtual env, but I can not index it
I have installed the module: (env) $ pip3 install django-rest-swagger Successfully installed django-rest-swagger-2.2.0 openapi-codec-1.3.2 simplejson-3.17.0 My Project Python Interpreter is also the venv: Why I can not index it? -
Django Rest Framework query data is not json serialiable Error
This is my views: class BillDetailView(APIView): def get(self, request, format=None): bill = Bill.objects.get(flat__id='a flat id') return Response(bill) I know to get detailed data, we can use RetriveAPIView but I will not use it for some reasons for my business logic. That is why I am using APIView I am trying to Response the query data as you see but it firing following error: Object of type 'Bill' is not JSON serializable Can anyone help me how to Response the query data? If I pass a dictionary in Response method, It will work great but you it is bad practice for my case. I just Pass the queried data in Response method. Can anyone help me in this case? -
Unable to catch ElasticSearch Connection Error
I have a model that looks like this: class Topic(models.Model): name = models.CharField(max_length=50, unique=True) def indexing(self): try: connections.create_connection() obj = TopicIndex( meta={'id': self.id}, name=self.name, ) obj.save() return obj.to_dict(include_meta=True) except ConnectionError: raise ValidationError("Something is wrong.") Whenever a new Topic is saved, it also saves it into ElasticSearch. However, let's say ElasticSearch is down. If I save a new Topic, I'll start getting errors like this: elasticsearch.exceptions.ConnectionError: ConnectionError(: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it) The error makes sense, however, I never catch it. "Something is wrong." never gets displayed. Instead, a connection tries to be made over and over again. -
What happens after executing the 'python manage.py runserver' command?
I am curious to know what all steps occur at the execution of the 'python manage.py runserver' command. -
GraphQL django with relay implementation not able to fetch particular ID
My node looks like - class CustomNode(graphene.relay.Node): """ For fetching object id instead of Node id """ class Meta: name = 'Node' @staticmethod def to_global_id(type, id): return id class ReportFileNode(DjangoObjectType): database_id = graphene.Int() class Meta: model = ReportFile interfaces = (CustomNode,) filter_fields: List[str] = ['id'] convert_choices_to_enum = False And my graphql query schema is like - class Query(graphene.ObjectType): all_report_files = DjangoFilterConnectionField(ReportFileNode) But when I query like this : query { allReportFiles(id: "367") { edges { node { id } } } } I get returned all the records and not just the one I queried. Also I have one more requirement that I should be able to input a list of ids and only those records should be fetched. -
Setup django social auth with vuejs frontend
I just started a project with a frontend developer. We are trying to add social authentication (Discord), without success. I want to use django as a REST API for the backend, I installed django-allauth which seems to work when I use a django template to connect using Discord: {% load socialaccount %} {% providers_media_js %} <html> <head> <title>Discord Registration</title> </head> <body> {{user}} <a href="{% provider_login_url "discord" method="oauth2" %}">Discord Connect</a> </html> But I have no idea how to share this connection with the frontend (made with vuejs). I've never worked on a project where backend and frontend are not in the same application... What to do on the frontend and what to do on the backend? And the main question, how? I've been working on it for two days and I'm still completely lost. -
GeoDjango multipolygon to polygon
As the title says how can I convert an entire database of geodjango models with geom fields of multipolygons into single polygons? The geojson is massive and I don't need multipolygons for zip codes. -
how to do HTML/CSS positioning
I am new to html and css so im sorry for asking this Q but how do you manage more than 1 item in html it seem so hard....im trying to have a image and a hover effect to it and have a text beneath this effect and then have a gallery beneath it .....pls suggest me the ways to do so. I'll include the code i've written below and this is for a django website so some contents may be different from actual html/css. Thanks in advance :) html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hey</title> <link rel="stylesheet" href="{% static "portofolio/css/cc.css" %}"> </head> <body> <div class="card"> <img src="{% static 'portofolio/img/save.png' %}" alt="Card Back"> <img src="{% static 'portofolio/img/try.png' %}" class="img-top" alt="Card Front"> </div> <div class="text"> <h1>Hello. This is me</h1> </div> </body> </html> css: body{ background-color: black; } .card { position: relative; display: inline-block; } .card .img-top { display: none; position: absolute; top: 0; left: 0; } .card:hover .img-top { display: inline; } .text{ color: white; font-family: 'TYPOGRAPH PRO',sans-serif; margin-left: 500px; margin-bottom: 500px; } -
Django: Querying two tables based on URL slug
I have created a database of music Producers and their Samples. class Producers(models.Model): producer_id = models.AutoField(db_column='Producer_ID', primary_key=True, blank=True, null=False) # Field name made lowercase. slug = models.SlugField() name = models.TextField(db_column='Name') # Field name made lowercase. info = models.TextField(db_column='Info', blank=True, null=True) # Field name made lowercase. image = models.ImageField(null=True, blank=True) class Meta: managed = False db_table = 'producers' class Samples(models.Model): song_id = models.AutoField(db_column='Song_ID', primary_key=True, blank=True, null=False) # Field name made lowercase. producer = models.ForeignKey(Producers, models.DO_NOTHING, db_column='Producer_ID') # Field name made lowercase. artist = models.TextField(db_column='Artist') # Field name made lowercase. title = models.TextField(db_column='Title') # Field name made lowercase. class Meta: managed = False db_table = 'samples' I have set up Slug Urls directing to the according Producer. ex) "producers/j-dilla/" I want each producer's bio to list their samples. Tried utilizing def bio(request, slug): producer_list = Producers.objects.all().filter(slug=slug) samples_list = Samples.objects.all() queryset = sorted( chain(producer_list, samples_list), key=lambda instance: instance.producer_id) {% for sample in queryset %} <li> <span>Artist: {{ sample.artist }}</span> <br/> <span>Title: {{ sample.title }}</span> <br/> <span>Title: {{ sample.producer_id }}</span> <br/> <hr/> </li> {% endfor %} returns the entire database of samples. -
How to get data from 2 different models in Django
I am new at this, trying to learn new django and python tricks I am making a project where authors can upload a design, the name of this app is "score" where there model.py as shown below: score app model.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='') I also have another app which is called "core" where there is an Item model. I want to be able manually from the admin to chose the name of the author and in the next design choice i only get his uploaded designs. I know I have to make a tuple of choice here is the core app model.py class Item(models.Model): title = models.CharField(max_length=100) author = models.CharField() design= models.ImageField()