Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No thumbnail migrations appear - Django 2.2
I did step by step to implement sorl-thumbnail in my django project. But no migrations thumbnail created so images do not get added via sending form but still get added by admin interface. I use: Python 3.9 Django 2.2.16 Pillow 9.3.0 sorl-thumbnail 12.9.0 What I did. pip install pillow, sorl-thumbnail In INSTALLED_APPS added 'sorl.thumbnail' In template -
when POST order summary, how do i assign quantity to each product mentioned
Im building e-commerce app. During checkout, the id of products inside the cart (and other info) get POSTed to ORDER table on my backend. My ORDER table has many-to-many relation with PRODUCT table, I cant figure out a smart way of saving on the server, how much of each product was in the cart during the checkout I was thinking of adding a second HelperORDER table where i would combine quantity and product.id but that doesnt seem very elegant. Here is how the structure of ORDER looks when you GET it "id": 11, "product": [ { "id": 1, "name": "gloomhaven" }, { "id": 2, "name": "mtg" } ], "order_date": "2022-11-14", "notes": "testaasdasdsadadadaaaaORDER", ideally it would look like this but i cant figure out how to handle it elegantly "product": [ { "id": 1, "name": "gloomhaven" "quantity" 2 }, { "id": 2, "name": "mtg" "quantity" 3 } ], -
django model database authorization
Hi i try to create an todo app which user can login and register.All of my user will be able to access to others 'task' just by changing the id of the 'task' in the url. let say testuser1 have 3 task in database which is /task/1/ , /task/2/ and /task/3 testuser2 have 2 /task/4/ and /task/5/. while i login into testuser2 i could just change the url to /task/2/ to view the task from testuser1 . how can i avoid that? models.py ` from django.db import models from django.contrib.auth.models import User # Create your models here. # one user can have many tasks (ONETOMANY) class Task(models.Model): priority_status = [ ('3', 'Prior'), ('2', 'Medium'), ('1', 'Low'), ] user = models.ForeignKey(User, on_delete = models.CASCADE,null =True , blank =True) title = models.CharField(max_length=100) description = models.TextField(max_length=255, null=True ,blank=True) priority = models.CharField(max_length=20,choices=priority_status, default='1') complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['complete','-priority'] views.py ` from django.shortcuts import render ,redirect from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView,DeleteView, FormView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login from .models import Task # … -
DRF How to save current user
I'm Trying to save an Item with the user's officeid but it's throwing me an error ValueError: Cannot assign "<CustomUser: admin@gmail.com>": "ClearanceItem.office" must be a "Office" instance. My customuser has id of 1 while the email is admin@gmail.com lastly the officeid = 'OSA' this is my models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) userid = models.CharField(null=True, max_length=9) officeid = models.ForeignKey('Office', models.DO_NOTHING, db_column='officeid', blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('Office', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(default='False', blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(auto_now_add = True, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' class Office(models.Model): office_id = models.CharField(primary_key=True, max_length=50) office_name = models.CharField(max_length=200) office_head = models.CharField(max_length=8, blank=True, null=True) designation = models.TextField(blank=True, null=True) office_parent = models.CharField(max_length=50, blank=True, null=True) deptlogo = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'office' this is my views.py class APIClerkView(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] serializer_class = … -
Grouping by category in DRF
I am trying to do something like this stack overflow question: Django RestFramework group by But I am trying to follow the instructions and it just isn't working for me. Here's my view: class ArticleListView(generics.ListAPIView): queryset = Page.objects.select_related().all() serializer_class = GroupPageListSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter) pagination_class = LimitOffsetPagination ordering_fields = ['date'] filter_class = ArticleMultiValue And here is my serializer. I can include my GroupPageSerializer serializer too, but I don't think it might be relevant? class GroupPageListSerializer(serializers.ModelSerializer): image = Base64ImageField(max_length=None, use_url=True) category = serializers.PrimaryKeyRelatedField( many=True, queryset=Category.objects.all()) url = serializers.CharField(allow_null=True, required=False, default=None, allow_blank=True) english = serializers.CharField(source="base", required=False, allow_blank=True) per_language = PerLanguageCondensedSerializer(many=True, required=False, read_only=True) foreign = serializers.CharField(required=False, allow_null=True, allow_blank=True) base = serializers.CharField(required=False) def to_representation(self, data): iterable = data.all() if isinstance(data, models.Manager) else data return { category: super().to_representation(Page.objects.filter(category=category)) for category in Category.objects.all() } class Meta: model = Page fields = ['per_language', 'date','base', 'foreign', 'english', "id", "category", "title", "image", "sound", "url", "slug"] How do I get an output like this: [{"CategoryName1":[ { "id": 5, ... }, { "id": 6, ... }, { "id": 7, ... } ] }, ... ] -
How can I do to access to a foreign key in the other side using Django and GraphQL?
I am working a on projects using Django. Here is my models.py : ` class Owner(models.Model): name = models.CharField(max_length=200) class Cat(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) pseudo = models.CharField(max_length=200)` My schema.py : `class Query(graphene.ObjectType): owner = graphene.List(OwnerType) def resolve_owner(self, info): return Owner.objects.first().cat_set.all()` But my problem is when I do that graphQL query : query{ owner{ name cat{ pseudo } } } it does not work whereas I would like something like that : ` `{ "data": { "owner": [ { "name": "Peter", "cat": { "pseudo": "miaou" } } ] } }`` How can I do that ? Thank you very much ! -
Restrict access per customer in django
I an trying to restrict access to records based on each customer so users cant access each others data through URL. I have added this but its restricting everything. Please help. if request.user.customer != Infringement.customer: return HttpResponse('Your are not allowed here!!')" views.py @login_required(login_url='login') def infringement(request, pk): if request.user.customer != Infringement.customer: return HttpResponse('Your are not allowed here!!') infringement = Infringement.objects.get(id=pk) notes = infringement.note_set.all().order_by('-created') if request.method == "POST": note = Note.objects.create( customer=request.user.customer, user = request.user, infringement = infringement, body=request.POST.get('body') ) return redirect('infringement', pk=infringement.id) context= {'infringement': infringement, 'notes': notes} return render(request, 'base/infringements.html', context) -
ModuleNotFoundError: No module named 'authlib'
I am trying to import the Authlib JTW token validator using from authlib.oauth2.rfc7523 import JWTBearerTokenValidator to integrate Auth0 into my Django app however I keep getting a ModuleNotFound error. I have Authlib already installed and have confirmed this using pip freeze so I am unsure why I keep getting this error. I have uninstalled and tried different versions of Authlib and am still encountering the same error. -
How can I insert in Wagtail the buttons to add and edit foreign key value like Django admin panel?
I would like to have in my Wagtail Admin Panel these buttons that are present in the Django Admin Panel. DjangoAdmin buttons Unfortunately I didn't find anything related. -
How is "secret_key.txt" more secure in Django project?
I apologize if this is a duplicate question but I can't find an answer online. In Django Checklist Docs I see the following to keep secret key secure. with open('/etc/secret_key.txt') as f: SECRET_KEY = f.read().strip() My project is deployed with AWS EBS. I've created a separate file called "secret_key.txt" which holds the key. How is this more secure than keeping the key in the settings.py config file? If someone can access my projects settings.py file to access the key, would they not be able to access the "secret_key.txt" file as well? How is creating a "secret_key.txt" file more secure? I've checked Google and Stack Overflow for reasoning but can't find an answer. Currently all sensitive information is protected using an .env file and including this file in .gitignore. -
Correct way to close down RabbitMQ and Celery?
I'm using Django to call a Selenium script through Celery and RabbitMQ as a message broker. The problem I'm having is often changes I make to my Selenium script aren't actually changing anything when I rerun my Django server. It sounds weird but I feel like something is still using my old code, not the one with the changes I make. My guess is that this is something to do with RabbitMQ being kept running while I make changes to my Selenium script? Do I need to 'refresh' it somehow each time I make changes or re-start the process? Also, I just ctrl+C to close everything when I'm finished, is there a 'proper' way to close down each time? -
Save customer in the background on django forms
Hi I am trying to automatically save the customer on post without having to list it in the forms. It currently shows the drop down and saves correctly but if I remove customer from forms.py it doesn't save anymore. I think I need to add something in the views but not sure what I am missing? views.py @login_required(login_url='login') def createInfringer(request): customer=request.user.customer form = InfringerForm(customer=customer) if request.method == 'POST': form = InfringerForm(customer, request.POST) if form.is_valid(): form.save() return redirect('infringer-list') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringerForm(ModelForm): def __init__(self, customer, *args, **kwargs): super(InfringerForm,self).__init__(*args, **kwargs) self.fields['customer'].queryset = Customer.objects.filter(name=customer) self.fields['status'].queryset = Status.objects.filter(customer=customer) class Meta: model = Infringer fields = ['name', 'brand_name','status','customer'] -
How to assign django permissions for object creators?
is it possible to allow editing on django admin site of objects in database only for creators of these objects? is extension django-guardian essential for this case? as i understood with django guardian i need manually assign permissions for each db objects and it seems not effective I tried to use django-guardian for this case, but documentation for it is not very clear for me and I am not sure this extension solve this case -
How do I get uuid foreign key to save in a form in django?
I have built a model with a uuid as the primary key. When I try to update using the uuid to identify the entry I am getting a valuetype error which says the object_id needs to be an integer. My Model: class IPHold(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) CHOICES = [ ('1', 'Book'), ('2', 'Documentary'), ('3', 'Graphic Novel/Comic'), ('4', 'Journalism'), ('5', 'Merchandise'), ('6', 'Podcast'), ('7', 'Stage Play/Musical'), ('8', 'Video Game'), ] media_type = models.CharField(max_length=1, choices=CHOICES, blank=False) title = models.CharField(max_length=255, blank=False) author_creator = models.CharField(max_length=255, blank=True) production_company = models.CharField(max_length=255, blank=True) artist = models.CharField(max_length=255, blank=True) composer = models.CharField(max_length=255, blank=True) publisher = models.CharField(max_length=255, blank=True) producer = models.CharField(max_length=255, blank=True) director = models.CharField(max_length=255, blank=True) year_published = models.ForeignKey(YearHold, on_delete=models.CASCADE, related_name='year_published', blank=True) # published_through = models.ForeignKey(YearHold, on_delete=models.CASCADE, related_name='published_through', default='0') ip_image = ResizedImageField(blank=True, size=[360, 360], force_format='JPEG', upload_to='media/ips/%Y/%m/') logline = models.TextField(blank=True) summary_description = models.TextField(blank=True) BOOKS = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10+'), ] series_length = models.CharField(max_length=2, choices=BOOKS, blank=True) episodes = models.PositiveSmallIntegerField(default=0) other_formats = models.BooleanField(default=False) genres = TaggableManager(through=TaggedGenreHold, verbose_name='Genres', blank=True) tags = TaggableManager(through=TaggedTagHold, verbose_name='Tags', blank=True) AVCHOICES = [ ('1', 'Available'), ('2', 'Optioned'), ('3', 'Purchased'), ('4', 'Public Domain'), ] availability = models.CharField(max_length=1, choices=AVCHOICES, blank=True) minimum_option_price = models.PositiveIntegerField(default=0) … -
Django: Custom User Model with Autoincrementing Id
I am trying to use Django Authentication and I want to create a custom model for the user that has an autoincrementing integer as id. I know about uuid library, but I want the id to be an integer number, that is why I want to avoid it. My code looks like: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, email, username, avatar, password=None): if not username: raise ValueError('User must have an username') if not avatar: raise ValueError('User must have an avatar') user = self.model( email=self.normalize_email(email), username=username, avatar=avatar, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, username, avatar, password): user = self.create_user( email=self.normalize_email(email), username=username, avatar=avatar, password=password, first_name=first_name, last_name=last_name ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) avatar = models.CharField(max_length=200) # required is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'id' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'email', 'avatar'] objects = MyAccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True The … -
how in javascript select some models field from django?
Hi i start learning javascript and i have a question. How in javascript select some models field from django? I searched this question in goggle but don’t get a current answer. -
Django model filter with "exact" IN operator
I want to find all users who have exactly same tags like a particular category (exactly same tags and also same amount of tags assigned) Something like... category = Category.objects.first() User.objects.filter(tags__in=category.tags.filter()) But this returns also users who share even only one tag with the category. Models are class User(models.Model): tags = models.ManyToManyField(Tag, blank=True, related_name='users') class Category(models.Model): tags = models.ManyToManyField(Tag, blank=True, related_name='categories') class Tag(models.Model): name = models.CharField(max_length=255, blank=False) Any solution appreciated. -
Django async access to related objects from .aget()
I have done some extensive searches and read the documentation. Unfortunately I could not solve the following. I probably missed something. ` async def generate_quotes(request, id): try: interrogation = await Interrogation.objects.aget(id=id) except Interrogation.DoesNotExist: return JsonResponse("Interrogation does not exist") print(interrogation.address.postcode) #where address is a onetoone related object with related name address i get a keyerror for address anddjango.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.` I am stuck on how to proceed. I have tried sync to async in all manner of ways with that one print statement and still nothing. I cant seem to get to the address object through its related interrogation object query result. I thought maybe it's to do with caching related objects. Any help would be greatly appreciate ! Thanks -
Why is the data being passed to the serializer saving as null in the database?
I've been working on this Django project with a rest framework serializer to take info sent from the front-end organize it and save it in the database. The info is made by drawing boxes over input fields on forms and sending all the fields you define. However, it's as though the data isn't actually being used after defining DataSerializer(data=data). An example of request.data = {'TextField': [], 'DateField': [], 'SignatureField': [['FieldName', [129, 79], [138, 35], 'Form.jpg']]} Here's my serializer: Class DataSerializer(serializers.ModelSerializer): class Meta: model = FormData fields = ["FieldName", "StartX", "StartY", "width", "height", "JSONData", "FormType"] def create(self, **validated_data): print(**validated_data) return FormData.objects.create(**validated_data) Here's my post View @api_view(['POST']) def create_list(request): if request.method == 'POST': dataDict = request.data for info in dataDict: Field = dataDict[info] stringDict = str(dataDict) for object in Field: datadict = { "FieldName": object[0], "StartX": object[1][0], "StartY": object[1][1], "width": object[2][0], "height": object[2][1], "JSONData": stringDict, "FormType": object[3] } serializer = DataSerializer(data=datadict) if serializer.is_valid(): serializer.create() return JSONResponse(serializer.data, status=201) print(serializer.errors) return Response("Not Valid") Here's my model which has been modified to accept null values not gonna be the case after I figure this out. class FormData(models.Model): FieldName = models.CharField(max_length=100) StartX = models.IntegerField(null=True) StartY = models.IntegerField(null=True) width = models.IntegerField(null=True) height = models.IntegerField(null=True) JSONData = models.CharField(max_length=500) … -
django-filter python class sub function under __init__ function not receive value return
I'm coding a django project that use django-filter: filter.py: import django_filters from myApp.models import MyRunStats class MyRunStatsFilter(django_filters.FilterSet): def gen_choice(filed): return tuple((l, l) for l in list(AegisRunStats.objects.values_list(filed, flat=True).distinct())) name_procss=django_filters.ChoiceFilter(label='Process',choices=gen_choice('name_procss')) class Meta: model = MyRunStats fields = ['name_procss'] For some reason I need to add a init function: class MyRunStatsFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(MyRunStatsFilter, self).__init__(*args, **kwargs) def gen_choice(filed): return tuple((l, l) for l in list(AegisRunStats.objects.values_list(filed, flat=True).distinct())) name_procss=django_filters.ChoiceFilter(label='Process',choices=gen_choice('name_procss')) class Meta: model = MyRunStats fields = ['name_procss'] But after modify the code ,the gen_choice function is not called . My question is how to call gen_choice() functioin again after I put it under def __init__(self, *args, **kwargs): -
Saving logs in Mongodb as 2nd DB in Django app
I need to save all request logs in Mongodb in Django. Can you provide me with some tutorial or blog? I tried searching but could not find any good post about this. -
CustomUser has no customer error for users signed in with google
I have a CustomUser model to differentiate between customer and merchant. class CustomUser(AbstractUser): is_customer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) Now the customers have the add to cart functionality for which I have a utils.py def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems':cartItems ,'order':order, 'items':items} As per the utils.py I always need request.user.customer. The customer instance here is created during customer registration. forms.py: @transaction.atomic def save(self): user = super().save(commit=False) user.is_customer = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.username=self.cleaned_data.get('username') user.email=self.cleaned_data.get('email') user.phone_number=self.cleaned_data.get('phone_number') user.address=self.cleaned_data.get('address') user.save() customer = Customer.objects.create(user=user) customer.first_name=self.cleaned_data.get('first_name') customer.last_name=self.cleaned_data.get('last_name') customer.username=self.cleaned_data.get('username') customer.email=self.cleaned_data.get('email') customer.phone_number=self.cleaned_data.get('phone_number') customer.address=self.cleaned_data.get('address') customer.save() return user So with the customer, everything worked just fine. But the problem arises when I try to sign in with google. I have signed in with google functionality with Oauth, worked on the google developers console, installed required packeges, and made changes to settings.py. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'projectapp.apps.ProjectappConfig', 'django_extensions', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
How to make JWT Token Authentication on pure Django without React?
I am backend dev, and I want to make website without front end, like react or other front end libraries, just on pure Django. I made on Django a website, all is done, and now it is time for JWT Token Authentication. Is it possible to make it on pure Django, if yes can you give me a hint how, the best will be some videos or done projects. Thanks in advice :)) -
Django add function to "from" clause?
I'm trying to write a Django query that generates the following: select group_id, cardinality(array_agg(distinct aul)) from report_table, unnest(active_user_list) as aul group by group_id Where active_user_list is an array[int] type. I'm trying to get a count of the unique items in the arrays of all rows that are in a group. The queryset.extra method gets me very close to this, but adds double quotes around unnest(active_user_list) as aul and doesn't work. I created a custom sql function that does work, but I'd prefer to do it in Django if possible. -
django-filter caused sqlite3.OperationalError: no such table issue
I'm coding a django project using django-filter: filter.py: import django_filters from myApp.models import MyRunStats class MyRunStatsFilter(django_filters.FilterSet): def gen_choice(filed): NAME_PROCESS_LIST = list(MyRunStats.objects.values_list(filed, flat=True).distinct()) NAME_PROCESS_CHOICE = tuple((l, l) for l in NAME_PROCESS_LIST) #this above 2 line codes will generate a tuple like NAME_PROCESS_CHOICE = (('One', 'One'), ('Two', 'Two')) return NAME_PROCESS_CHOICE name_procss=django_filters.ChoiceFilter(label='Process',choices=gen_choice('name_procss')) class Meta: model = MyRunStats fields = ['name_procss'] views.py: from myApp.models import MyRunStats from myApp.filter import MyRunStatsFilter def runstat_hist_view(request): all_obj = MyRunStats.objects.all().order_by('-create_dttm') hist_filter = MyRunStatsFilter(request.POST, queryset=all_obj) paginator= Paginator(hist_filter.qs[:75], 15) 'logic and code here....' While I'm using django-filter,when I tried to: python manage.py makemigrations or python manage.py migrate or python manage.py mangage.py runserver I always met the error: sqlite3.OperationalError: no such table issue I googled and found all the solutions are not work for me .But finally I manfully solved the issue by: First in Veiws.py I commend this line: from myApp.filter import MyRunStatsFilter And then run any of above 3 command line ,it works ,the server can up and then I commend that line back. Everything goes well, but this method is very manually. Once I upload the code to a automatically testing sever the issue comes again ,since it is solved manfully ,in the testing sever I need find out …