Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Django foreign key field with to_field attribute
I have my model of User object which is related to Group object (example). So user has something like: group_name = models.ForeignKey(Group, to_field="group_name", ...) (of course the group_name is defined as unique as it's not a primary key in Group object) But when I'm trying to change the group_name value for some Group object (regardless it's via Admin interface or within the code by updating the selected object) it raises the Integrity error: FOREIGN KEY constraint failed I know there is a mandatory parameter on_delete for the foreign key filed but I've tried all potential pre-defined values (models.SET_DEFAULT, models.CASCADE, etc.) but without any change. It seems to me I need something what to do on_update, but that's not possible attribute ;-) Thanks -
Side bar menu should load based on role based login django
Based on the Designation, Menu should load while the Employee login to the application. Its like a role based login or Access control permision -
django ORM problem - Annotate and aggregate return inconsistent values
I found a setup where aggregate() and annotate() do NOT return the same values... I am really confused. I have the following models: class Invoice(models.Model): pass class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, related_name="items") amount = models.PositiveIntegerField(null=False, blank=False, default=1) price = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False, default=0) begin = models.DateField(null=True, blank=True) When I want to get the total revenue over a timespan, I have the following query: revenue = Invoice.objects.annotate( first_date=Min('items__begin')).filter( first_date__range=[start_date, end_date]).aggregate( revenue=Sum(F('items__amount') * F('items__price'), output_field=FloatField()))['revenue'] I tried to do the same with annotate() just to verify the results: revenue_list = Invoice.objects.annotate( first_date=Min('items__begin')).filter( first_date__range=[start_date, end_date]).annotate( revenue=Sum(F('items__amount') * F('items__price'), output_field=FloatField())) When I now loop over the elements and manually sum up revenue I get a different value than revenue. Any ideas? Unfortunately after an aggregation you cannot check the raw query anymore... Thanks! -
Generate PDF in Django Python with customize header/footer and different header/footer in different pages in a single pdf
I want to generate pdf using django python. Pdf will have customize headers and footers and different headers and footers on different pages in a single pdf file. I have already tried WKHTML but it doesn't give option of different headers and footers in a single file. WKHTML Library Expecting: Different headers and footers on different pages in a single pdf file. -
How to retrive data from related table in djnago
Hey I want retrieve all staff information with there respective Operating Hours please help me, Here is my models class Staff(models.Model): vendor = models.ForeignKey(Vendor,on_delete=models.DO_NOTHING,blank = True) name = models.CharField(max_length=100) last_name = models.CharField(max_length = 100) gender = models.IntegerField(choices=GENDER_TYPE, default=0) class OperatingHours_staff(models.Model): staff = models.ForeignKey(Staff,related_name='days',on_delete = models.CASCADE) day = models.IntegerField(choices = constants.DAYS) start_time = models.TimeField() end_time = models.TimeField() Thanks in Advance -
Where does ArrayField create SimpleArrayField in Django?
I want to review the code and maybe override it for my needs, where SimpleArrayField is created for ArrayField in Django. Unfortunately I can't find or don't understand where it happens. I've searched through ArrayField and only place where SimpleArrayField is mentioned is this method. Since method returns super().formfield(...'form_class': SimpleArrayField...), I've searched for formfield() in inherited classes (CheckFieldDefaultMixin, Field), but found nothing. -
DRF loading binary files sending from React app
I made a standard API for downloading files to AWS S3. Using the standard DRF interface, the files are loaded correctly into the repository. models.py class Documents(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) upload = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=64) datafile = models.FileField() created = models.DateTimeField(auto_now_add=True) type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) views.py class DocumentsListView(AwsUrlMixin, viewsets.ViewSetMixin, generics.ListCreateAPIView): queryset = Documents.objects.all() serializer_class = DocumentsSerializer permission_classes = (IsAuthenticated, LifeLinePermissions) pagination_class = None def perform_create(self, serializer): serializer.save(author=self.request.user) Problems begin when the download is done through the user interface and the file is transferred using React. The file comes in binary form, and django does not accept this format by saying datafile: ["No file was submitted."] An error occurs in the django console HTTP POST /api/v1/files/ 400 [0.02, 127.0.0.1:33916] In the browser debugger -
How to implement upload image via url in django
Basically I am creating a website where you can upload images of different websites using url. How to implement it. How to validate if it is an image and how to fetch it and store in your database -
how to remove or delete django project
screenshot image1 I use visual studio code and create a django project(python-training).Q1:I can't use 'open with live server' to see html file, instead the file in python-training directory. what I can do to remove or delete django project? Q2:why the python-training directory don't have the following files: setting.py, manage.py thank you all for give me a hand screenshot image2 screenshot image3 -
Memcached reflecting changes automatically from the built in User model, how?
I am using memcached in my code to represent some lists in web. I am doing something like this, from django.core.cache import cache #inside view cache_key='somekey' cache_time=sometime data=cache.get(cache_key) if not data: #some code cache.set(cache_key,data,cache_time) return render(...) It is working perfectly. Cache is serving the pages. But here I am observing that, any changes in the database in the build in User model is getting reflected in the cache automatically. how is this happening? And my 2nd question is, what is the best way to reflect the database changes in the memcached. I already tried to maintain, flags in the database using a trigger. It is working, but it is not possible to maintain different flags for every cache in the db as some urls has in them. Any help will be appreciated.. -
Any Suggestions please
I am building a website for image hosting. People can upload via url or images directly from their device. Trying to implement it on python / Django but not getting the proper tutorials. Any suggestions? Should I use aws s3 for storage and ec2 for server. Any suggestions? I am lost. -
Django: Request data is missing while calling view from view
I am calling view from another view in for loop. First time, view is processed properly but next time request object is empty. for index, component in enumerate(components_list): AggregateData.as_view()(request._request, nquery=index) Here for second iteration request object is empty (request is <QueryDict: {}>). Not sure where I am going wrong. -
Django defining custom routing rules
I come from a TypeScript/Express.js background when it comes to developing APIs, and normally we have a custom AuthRouter that we structure similar to below (implementation scrubbed for client security). We do our auth by taking a Bearer token and sending it to an external API for validation: // app.ts /* Express app setup */ app.use(AuthRouter); /* Other modules that define our other app routes/services */ // AuthRouter.ts router = express.Router() router.all(config.API_BASE + '*', async (req, res, next) => { validate(req.headers.authorization) next(); }); Is there a similar way to achieve the same routing flow in Django? I've already looked into defining a custom Authentication Backend, but I'm afraid it won't play nice since it appears to be coupled to a "User" which isn't the goal, so i can't satisfy the minimum requirements. Is leaving the get_user function empty a valid approach? Ideally, I'm looking for whatever can simulate that next() callback that Express provides. If I have to setup the callback functionality myself, I will, although I think that could get pretty hairy. Any tips would be appreicated!! -
How to solve multiple http request in django googlesearch?
Actually I know the reason why this error is coming but dont know how to solve it. This problem came because of captchas which comes when anything is searched in the google.com. How to remove it .Or there is any alternative to do this. from googlesearch import search for i in search("query",tld='co.in',lang='en',num=10,stop=1,pause=2): print (i) I have already tried by reducing the resting period of the google search. -
Celery & channels conflict
I'm using the latest celery and channels.But I found that when I use channels,My celery can't receive task submit by djano.When I close the channels in django, Celery works well.Dose channels and celery has something conflict? My channels config is: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [("redis://:*@127.0.0.1:6379/4")], }, }, } My celery config is: CELERY_ACCEPT_CONTENT = ['application/json',] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' BROKER_URL = 'redis://:*@127.0.0.1:6379/3' CELERY_RESULT_BACKEND = 'redis://:*@127.0.0.1:6379/2' And I just use python manage.py runserver to start django and channels -
Multiple subdomains with django
I'm trying to run two applications on a webserver with Django + Apache at signal.server.com and noise.server.com. Currently both URLs point to singal.server.com I've been changing options around to no avail. Here is my virtual host for the server.com which works fine WSGIPythonPath /var/www/html/d_signal WSGISocketPrefix run/wsgi <VirtualHost *:80> ServerAdmin hello@mail.server.com ServerName www.server.com DocumentRoot /var/www/html <Directory /var/www/html/> Options Indexes FollowSymLinks AllowOverride All </Directory> ErrorLog /var/log/httpd/server.error.log CustomLog /var/log/httpd/access.log combined <IfModule mod_dir.c> DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm </IfModule> </VirtualHost> virtual config for singal.server.com <VirtualHost *:80> ServerAdmin hello@server.com ServerName signal.server.com ServerAlias signal.server.com DocumentRoot /var/www/html/d_signal/d_signal WSGIScriptAlias / /var/www/html/d_signal/d_signal/wsgi.py WSGIDaemonProcess signal.server.com python-home=/var/www/html/d_signal/signal_env socket-user=apache WSGIProcessGroup signal.server.com Alias /static /var/www/html/d_signal/static <Directory /var/www/html/d_signal/sig/templates/sig/static> #Require all granted </Directory> <Directory /var/www/html/d_signal/d_signal> AllowOverride all #Require all granted Options Indexes FollowSymlinks <Files wsgi.py> #Require all granted </Files> </Directory> </VirtualHost> And the virtual config for noise.server.com <VirtualHost *:80> ServerAdmin hello@server.com ServerName noise.server.com ServerAlias noise.server.com DocumentRoot /var/www/html/d_signal/noise WSGIScriptAlias / /var/www/html/d_signal/d_signal/wsgi_noise.py WSGIDaemonProcess noise.server.com python-home=/var/www/html/d_signal/noise_env socket-user=apache WSGIProcessGroup noise.server.com Alias /static /var/www/html/d_signal/static <Directory /var/www/html/d_signal/sig/templates/sig/static> #Require all granted </Directory> <Directory /var/www/html/d_signal/noise> AllowOverride all #Require all granted Options Indexes FollowSymlinks <Files wsgi_noise.py> #Require all granted </Files> </Directory> </VirtualHost> If I visit http://noise.server.com/noise/ then I get to the app I want to see. What am I missing here? -
How to get refresh token value within python / django social auth?
Strava is moving from forever tokens to refresh tokens. Part of my app portfolio is a website powered by django that uses python social auth and some django social auth bits to authorize users against their strava credentials. I'm able to get it working fine in the website but can't figure out how to get access to the refresh token values. I need the refresh token values given I have batch processes that use them to connect to strava and sync activities, etc. I expected them to be in the extra data field in the django db but alas only the token, the type and the auth_time are present. So far I've upgraded the following libraries to get this far: social_auth_core and social-auth-app-django. Any ideas? Perhaps I also need to upgrade python-social-auth? I'm assuming there is a oauth2 module that receives the direct with the extra data as url parameters. Just don't know what method that is... Thanks in advance for any suggestions. best, mike -
Using the Django admin site for specific instances of a model
I am working on my first Django app, and was thinking of using a rather abstract database schema, like this: class ListCategories(models.Model): name = models.TextField(max_length=200) type = models.TextField(max_length=200) class ListItems(models.Model): category = models.ForeignKey('ListCategories', on_delete=models.CASCADE) item = models.TextField(max_length=200) sorstorder = models.IntegerField() class ObjectType(models.Model): name = models.TextField(max_length=200) class Object(models.Model): type = models.ForeignKey('ObjectType', on_delete=models.CASCADE) name = models.TextField(max_length=200) class ObjectTypeProperties(models.Model): name = models.TextField(max_length=200) object_type = models.ForeignKey('ObjectType', on_delete=models.CASCADE) list_category = models.ForeignKey('ListCategories', null=True, on_delete=models.CASCADE) class ObjectProperties(models.Model): object = models.ForeignKey('Object', on_delete=models.CASCADE) property = models.ForeignKey('ObjectTypeProperties', on_delete=models.CASCADE) list_item = models.ForeignKey('ListItems', on_delete=models.CASCADE) result = models.TextField(max_length=200) class HistoricalNumericalData(models.Model): object = models.ForeignKey('Object', on_delete=models.CASCADE) object_property = models.ForeignKey('ObjectProperties', on_delete=models.CASCADE) value = models.FloatField() class Image(models.Model): object = models.OneToOneField('Object',on_delete=models.CASCADE) image = models.ImageField() def image_tag(self): return mark_safe('<img src="{}"/>'.format(self.image.url)) image_tag.short_description = 'Image' This is very flexible on the DB, as you can add object types and object properties by simply adding lines to the DB. However, I would like to use the admin interface to add new Objects to the database, and this is where this schema is tricky to use. The form would need to be different for each object type, however, as they would have not the same properties. Is there a way to register models to use with the admin site that behave differently according … -
Django - Data query based on user permissions or user group name
I'm new to Python and started a project where I have a list of Customers that are distributed across different Regions of the world. System users should only have access to users in their own region I added custom permissions for the class Customer. I'm trying to find a way to list all the Customers in one or more regions (for example: latam, emea, us, ...) based on Authentication group name or user permission. Is that possible?? views.py class CustomerListView(PermissionRequiredMixin, LoginRequiredMixin, generic.ListView): model = Customer context_object_name = 'customers' template_name = 'customers/customer.html' login_url = '/' permission_required = 'customer.view_customer' permission_denied_message = 'User has no permission to perform this action.' model.py class Region(models.Model): region_id = models.AutoField(primary_key=True) region_name = models.CharField(max_length=12, unique=True) def __str__(self): return self.region_name class Customer(models.Model): class Meta: permissions = ( ("latam_view", "Can acceess LATAM data"), ("us_view", "Can acceess US data"), ("emea_view", "Can acceess EMEA data"), ) customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=15, null=False, blank=False, unique=True) primary_contact_name = models.CharField(max_length=24, null=False, blank=False) primary_contact_position = models.CharField(max_length=25, null=False, blank=False) primary_contact_department = models.CharField(max_length=15, null=False, blank=False) primary_contact_phone = models.CharField(max_length=17, null=False, blank=False) primary_contact_email = models.EmailField(max_length=30, null=False, blank=False) customer_region = models.ForeignKey(Region, on_delete=models.PROTECT, null=False, blank=False) auth_group = models.ForeignKey(Group, on_delete=models.PROTECT, null=False, blank=False) def __str__(self): return self.customer_name Thank you -
Django ORM with Rest API writing complex query
I wrote a functionality like if a person have related data, user cant perform update. Here you go for my models: class Person(models.Model): alias = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=20) class Appointment(models.Model): patient = models.ForeignKey(Person, related_name="patient_for_appointment", on_delete=models.CASCADE) data = models.CharField(max_length=20) class Sales(models.Model): customer = models.ForeignKey(Person, related_name="customer_for_sales", on_delete=models.CASCADE) amount = models.FloatField() class Prescription(models.Model): patient = models.ForeignKey(Person, related_name="Patient_for_prescription", on_delete=models.CASCADE) details = models.CharField(max_length=100) My primary key is UUID named alias this is my api view: from django.shortcuts import render from . models import Person, Appointment, Prescription, Sales from . serializers import PersonSerializers from rest_framework.generics import RetrieveUpdateDestroyAPIView from rest_framework.response import Response from rest_framework.exceptions import APIException class PersonView(RetrieveUpdateDestroyAPIView): queryset = Person.objects.all() serializer_class = PersonSerializers lookup_field = 'alias' def update(self, request, *args, **kwargs): # person = Person.objects.filter(alias=kwargs['alias']) appointment = Appointment.objects.filter(patient__alias=kwargs['alias']) prescription = Prescription.objects.filter(patient__alias=kwargs['alias']) sales = Sales.objects.filter(customer__alias=kwargs['alias']) partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if prescription: raise APIException('CANT UPDATE') elif appointment: raise APIException('CANT UPDATE') elif sales: raise APIException('CANT UPDATE') else: self.perform_update(serializer) return Response(serializer.data) Look closely above view some query: appointment = Appointment.objects.filter(patient__alias=kwargs['alias']) prescription = Prescription.objects.filter(patient__alias=kwargs['alias']) sales = Sales.objects.filter(customer__alias=kwargs['alias']) I implement here if a Person have sales or appointment or prescription, user can't to perform update and throw an error. Everything … -
reverse relationship serializer in not returning field in json response
I have this models: class User(AbstractUser): username_validator = CustomUnicodeUsernameValidator username = models.CharField( _('username'), max_length=20, unique=True, help_text=_('Required. 15 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField( _('email address'), unique=True, null=False, blank=False, error_messages={ 'unique': _("A user with that email already exists."), }, ) And a Profile model which extends the previous model with personal user information: class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, primary_key=True, parent_link=True, related_name='profiles', related_query_name='profile', on_delete=models.CASCADE ) bio = models.CharField( max_length=100, null=True, blank=True ) birth_date = models.DateField( null=True, blank=True ) avatar_url = models.CharField( max_length=100, null=True, blank=True ) cover_url = models.CharField( max_length=100, null=True, blank=True ) These are my serializers: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = get_user_model() fields = [ 'email', 'username', 'password', 'first_name', 'last_name', ] extra_kwargs = { 'password': {'write_only': True} } And for profile: class ProfileSerializer(serializers.HyperlinkedModelSerializer): profiles = UserSerializer( many=False, read_only=True ) class Meta: model = Profile depth = 1 fields = [ 'url', 'avatar_url', 'bio', 'birth_date', 'cover_url', 'profiles' ] I'm trying to get a response like the following when sending a GET request from http://localhost:8000/profiles/1/ : { "user": { "url": "http://www.tribsport.com:8000/users/1/", "username": "cthulhu", "email": "cthulhu@gmail.com", }, "url": "http://www.tribsport.com:8000/v1/profiles/1/", "avatarUrl": "assets/images/avatars/rick.jpeg", "bio": "Hincha de River Plate!", … -
MySQL or NoSql? What should I use for a custom "User" model
So I'm building a django-rest project for fun, I decided to use a NoSQL with the help of mongoengine (ODM for django) just to see how things will work out. My site will be like a marketplace mainly for trading music instruments. So I defined two models, one for the User and one for the Gear, the Gear model has a field of "owner" which references to the User model, while the user model has the field of "gears" which lists the posted gears he have for trading/selling. (Btw, in mongoengine, we define models as documents) I'm blocked by this specific question. How should I approach my custom "User" model? Should I store it in a relational database or it's fine to store it to a nosql? I already researched and saw that I'll lose most of django power just using a nosql (as expected) and also that storing a "User" model in a nosql is a bad idea as it is "relational". How can I know if my data is relational or not and if it's a great idea to store it into a relational db or not? I can't seem to wrap my mind with other explanations out … -
How to call a model method in views.py
I have a Post model with a custom model method that sets a post status to "DELETED" rather than actually deleting the Post object: STATUS_DRAFT = 0 STATUS_PUBLISHED = 1 STATUS_DELETED = 2 STATUS_CHOICES = ( (STATUS_DRAFT, 'draft'), (STATUS_PUBLISHED, 'published'), (STATUS_DELETED, 'deleted'), ) class Post(models.Model): title = models.CharField(max_length=30) status = IntegerField(choices=STATUS_CHOICES, default=STATUS_DRAFT) def retire(self): self.status = STATUS_DELETED self.save() pass I am using Generic Edit Views to handle my posts: class PostDeleteView(DeleteView): model = Post success_url = reverse_lazy('delete_post_success') I want to customise the delete method to instead call the retire method in my Post model: def delete(self, request, *args, **kwargs): """ Call the retire() method on the fetched object and then redirect to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.retire() return HttpResponseRedirect(success_url) However this syntax is incorrect (it does not change the Post.status) Where am I going wrong? -
What is a better way to query a ManyToManyField for speed? entire object or id only?
I'm trying to determine the most efficient way to query a ManyToManyField for speed. I have 2 options that I know of: Add the entire object to the field Add just the id to the field If I add the object, obviously with on_delete=models.CASCADE, I get that benefit, which is huge, but I'm afraid adding it might slow query speed down because it's getting an entire object, and many of them at that. Whereas with just the id, it's just an int, so less heavy, and faster I assume. For speed only, what would you suggest? -
Access HTTP_REFERER in django Generic Views
I want to pass the previous URL in a context variable for a generic view: class PostDeleteView(DeleteView, LoginRequiredMixin): previous_url = self.request.META.get('HTTP_REFERER') ... However, I can't access either self or request. How do I go about this?