Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update database on successful payment in django through paytm
https://dev.to/iiits-iota/paytm-payment-gateway-integration-in-django-1657 I referred this to setup my payment gateway -
Verify OAuth 2.0 token
I have a token from Microsoft OAuth 2.0 with PKCE that in is sent to my Django server from a front-end. How can I verify the integrity of this token? I want to allow users to sign in with their Microsoft accounts. -
How to limit ForeignKey users in custom groups in django
How to limit number of ForeignKey users in custom groups in django ? for example to 3? class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) -
Comparison in Django template using request.GET and choices is not properly evaluated
I have this in my models: class Task(Record): class Status(models.IntegerChoices): OPEN = 1, "Open" COMPLETED = 2, "Completed" status = models.IntegerField(choices=Status.choices, db_index=True, default=1) Then in my template I want to show all the statuses, so I do this in views.py: context = { "statuses": Task.Status.choices, } And in my template I loop through it: {% for label,name in statuses %} {{ label }}: {{ name }} {% endfor %} This leads to: 1: Open 2: Completed So far, so good. But now if I use a GET parameter, I can't get things to work as I want. Say I open ?id=2 and then I run: {% for label,name in statuses %} {{ label }}: {{ name }} {% if label == request.GET.id %} YES {% else %} Sorry, not equal to {{ request.GET.id }} {% endif %} {% endfor %} Then I expect this to show YES for the first item. But it doesn't! Somehow this evaluates to: 1: Open Sorry, not equal to 1 2: Completed Sorry, not equal to 1 I do not understand why the first item does not evaluate to true. -
Slow query using Django and PostgreSQL with > 40 million rows
I'm working with a model (table) with more than 40 million rows and queries are very slow (> 2 min), using PostgreSQL. The models: class ModelA(...): source = models.ForeignKey(ModelB, related_name='source', ...) target = models.ForeignKey(ModelB, related_name='target', ...) class ModelB(...): c = models.ForeignKey(ModelC, ...) ... The Django filter: ModelA.objects.filter(source__isnull=True, target__c=my_c) The query: SELECT "model_a"."id", ... FROM "model_a" INNER JOIN "model_b" T3 ON ("model_a"."target_id" = T3."id") WHERE ("model_a"."removed" = False AND "model_a"."source_id" IS NULL AND T3."c_id" = 389) How can I optimize it? I am having optimization problems and I would like to know different solutions, etc. -
Channels - how do I send data through websocket when signal is received?
I want to stream data from a database through websocket. Basically a new record is being inserted into DataModel at every second and I want to send this new record through websocket as soon as it's inserted. Someone recommended me to use signal when the model's save() method is called. So to my models.py I just added this: def save_post(sender, instance, **kwargs): print('signal') post_save.connect(save_post, sender=DataModel) What to I put inside of save_post and also on my consumers.py so that the data goes through? -
how can i define User Groups and permissions on django to control a news model?
i have News model. i want to manage news by users who belongs from these Groups? class News(models.Model): title = models.CharField(max_length=255, help_text="Short title of news") content = models.TextField(blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True) how can i define these user permissions? Users Groups Permissions Reporters # create a news CopyEditors # read and update Poducers # read, update, aprove and revoke Rundown # list of aproved articles Anchors # read only aproved articles -
Why can't I filter on one new field in Django Rest Framework?
So I'm editing an existing codebase using Django Rest Framework, and I added a new field to a model: class MyModel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=150, null=True) the_new_field = models.IntegerField(null=True, default=None) I've got a serializer, which is fairly basic: class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ( 'id', 'name', ) So to the serializer I simply added the new field: class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ( 'id', 'name', 'the_new_field', ) I can call the endpoint using name using ?name=awesomename, which actually filters based on awesomename, but when I call the endpoint using ?the_new_field=123456 it simply returns all the records in the database. What am I missing here? How can I make it filter based on this new field? -
Django / Wagtail: trying to add new children content to present on template
CandlePage and CandleIndexPage. the CandlePage is defined to describe the candle details the CandleIndexPage should present a list of Candles (CandlePage objects). i need to add to the CandleIndexPage template a 'label' property for each CandlePage object. i tough that it can be done with overriding the get_context method, but i was not able to do it on the 'children's level'. happy to get any advice. -
I got a KeyError when i try to use request.META['CSRF_COOKIE']
I want to use the mako template in django2, but when I set up the render function of mako and tried to set the template to bring the csrf token, I found that I could not get the CSRF__COOKIE in request.META #coding:utf-8 from mako.lookup import TemplateLookup from django.template import RequestContext from django.conf import settings from django.template.context import Context from django.http import HttpResponse def render_to_response(request, template, data=None): context_instance = RequestContext(request) path = settings.TEMPLATES[0]['DIRS'][0] lookup = TemplateLookup( directories=[path], output_encoding='utf-8', input_encoding='utf-8' ) mako_template = lookup.get_template(template) if not data: data = {} if context_instance: context_instance.update(data) else: context_instance = Context(data) result = {} for d in context_instance: result.update(d) result['csrf_token'] = '<input type="hidden" name="csrfmiddlewaretoken" value="{0}" />'.format(request.META['CSRF_COOKIE']) return HttpResponse(mako_template.render(**result)) django reports error: KeyError "CSRF_COOKIE", what shoud i do? -
Product image loads on all products page, but not on individual product page (Django)
For a little bit of context, when you add a new product to my website, you are required to add an image as well. I can get the product images to load just fine when viewing the main products page, but when you try to view an individual product on a new product details page, the image won't load. The product image is pulled in via the following code: <div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div> Here is the HTML used on the main products page: <div class="album"> <div class="container"> <div class="product-row"> {% for product in products %} <div class="col-xl-4 col-md-6"> <div class="card mb-4 shadow-sm"> <div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div> <div class="product-card-body"> <p class="product-title">{{ product.name }}</p> <p class="text-muted">{{ product.category }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <form method="post" action="{% url 'add_to_cart' product.id %}"> {% csrf_token %} <div class="text-center"> <span class="input-group-btn"> <button class="product-btns btn-success" type="submit">Add to Cart</button> </span> </div> </form> <form class="ml-2" method="post" action="{% url 'product_details' product.id %}"> {% csrf_token %} <div class="text-center"> <span class="input-group-btn"> <button class="product-btns btn-info" type="submit">Find out more</button> </span> </div> </form> </div> <p class="product-price">£{{ product.price }}</p> </div> </div> </div> </div> {% endfor %} </div> </div> </div> Here is the HTML used on the product … -
Uploaded image is not showing in django Admin using class based views?
I am using Class Based Views for uploading images but none of the images are getting uploaded i.e. the images are not shown in Django Admin Site. This is simple blog project where in only superuser can upload blogs/posts. Here are my major files of the project: models.py class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title=models.CharField(max_length=256) text=models.TextField() create_date=models.DateTimeField(default=timezone.now()) published_date=models.DateTimeField(blank=True,null=True) blog_pic=models.ImageField(upload_to='blog_pics/',blank=True)#the field for uploading image forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('author','title', 'text','blog_pic') views.py class CreatePostView(LoginRequiredMixin,CreateView): login_url='/login/' redirect_field_name='basic_app/post_detail.html' form_class=PostForm model=Post settings.py MEDIA_DIR=os.path.join(BASE_DIR,'media') STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,'static') MEDIA_ROOT=MEDIA_DIR MEDIA_URL='/media/' I also made the changes in the urls.py which is mentioned in docs but that didn't solved my problem. urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Please help me rectify the error due to which the image is not being uploaded. -
Null Value error inspite of passing value in Serializer
I have a model in my app like this: class Bid(models.Model): supplier = models.ForeignKey(User, on_delete=models.CASCADE) order = models.ForeignKey(Orders, on_delete=models.CASCADE) comments = models.CharField(max_length=255, blank=True, null=True) bid_amount = models.CharField(max_length=255, default=0) date = models.DateTimeField(auto_now_add=True) is_confirmed = models.BooleanField(default=False) I am trying to save data in this model but keep getting the error: django.db.utils.IntegrityError: null value in column "order_id" violates not-null constraint DETAIL: Failing row contains (28, null, 800, 2020-06-09 12:43:14.697672+00, f, null, 5). Views.py class BidCreateAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def post (self, request, pk, format=None): supplier = request.user.pk d = request.data.copy() print("pk", pk) d['order'] = pk d['supplier'] = supplier print("d is", d) serializer = BidSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer.py class BidSerializer(serializers.ModelSerializer): order = OrderSerializer(many=True, read_only=True, required=False) class Meta: model = Bid fields = "__all__" I have set required=False in order serializer then why does it throws the error ? -
Cannot edit data from a table in django
I keep on getting this error and I don't know why. Can anyone help me with it? NoReverseMatch at /item Reverse for 'edit_supplier' with arguments '('lll111',)' not found. 1 pattern(s) tried: ['supplier/edit_item/(?P\d+)/$'] models.py class item_status(models.Model): item_code=models.CharField(max_length=30,unique=True,primary_key=True,blank=False) item_name=models.CharField(max_length=50,blank=True) type= models.CharField(max_length=100,blank=True) price=models.IntegerField() choices =({'AVAILABLE','Item ready to be purchased'},{'SOLD','Item Sold'},{'RESTOCKING','Item restocking in few days'}) status=models.CharField(max_length=50,choices=choices,default="AVAILABLE") #Available,Sold, Restocking item_quantity_available=models.IntegerField() issues=models.CharField(max_length=100,default="No issues") views.py def edit_item(request, pk, model, cls): item = get_object_or_404(model, pk=pk) if request.method == "POST": form = cls(request.POST, instance=item) if form.is_valid(): form.save() return redirect('index') else: form = cls(instance=item) return render(request, 'inv/edit_item.html', {'form': form}) def edit_item_status(request, pk): return edit_item(request, pk, item_status, item_statusForm) forms.py class item_statusForm(forms.ModelForm): class Meta: model = item_status fields = ('item_code', 'item_name', 'type', 'price','status','item_quantity_available','issues',) urls.py url(r'^item/edit_item/(?P<pk>\d+)$', edit_item_status, name="edit_item_status"), index.html {% for item in items1%} <tr> <td>{{ item.item_code }}</td> <td>{{ item.item_name }}</td> <td>{{ item.type }}</td> <td>{{ item.price}}</td> <td>{{ item.status}}</td> <td>{{ item.item_quantity_available}}</td> <td>{{ item.issues}}</td> <td> <a href="{% url 'edit_supplier' item.item_code %}" class="btn btn-warning btn-sm" role="button" aria-pressed="true" > Edit</a> <a href="{% url 'delete_supplier' item.item_code %}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x</a> </td> </tr> {% endfor %} This code however works fine for my other classes that use integer primary key. I don't know why and I am totally lost now. -
django-tables2 accessing computed data
I am creating set(t)s as accumulation of parts and I want to display their total price according similar to this post: models.py: class PartBase(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Price", decimal_places=2, max_digits=8) class Sett(models.Model): name = models.CharField('Name', max_length=120) class PartRelation(models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") sett = models.ForeignKey(Sett, related_name='setts', on_delete=models.SET_NULL, null=True) def get_position_price(self): return self.qty * self.part.price tables.py: class SetTable(django_tables2.Table): total_price = django_tables2.Column(accessor="total_price", verbose_name="total") class Meta: model = Sett sequence = ("name", "total_price") exclude = ("id",) views.py: class SetListView(SingleTableView): model = Sett context_object_name = "setts" table_class = SetTable def get_context_data(self, **kwargs): context = super(SetListView, self).get_context_data(**kwargs) for s in context["setts"]: pr = PartRelation.objects.filter(sett=s) s.total_price = 0 for p in pr: s.total_price += p.get_position_price() return context def total_price(self): pos = PartRelation.objects.filter(sett_id=self.kwargs["pk"]) total_price = 0 for p in pos: total_price += p.get_position_price() return total_price I tried accessing the data via get_context and also via a custom method total_price, but neither worked. Where did I take the wrong turn? -
Pip package install in both globally and in virtualenv
I have a problem with installing my pip packages. I have created a virtualenv and when I try to install packages through pip, it gets install both globally and inside my virtualenv. Does anyone have any solution why this is happening? I want to solution to be for windows. -
How to do unitetesting for unmanaged apps in django.? [closed]
I have an application where I am using 3 tables from legacy db and one resides within the application db. I have tried the solution https://dev.to/vergeev/testing-against-unmanaged-models-in-django ,https://blog.birdhouse.org/2015/03/25/django-unit-tests-against-unmanaged-databases/ ,https://dev.to/vergeev/testing-against-unmanaged-models-in-django. But nothing seems to work. I run my scripts as follows: python manage.py test --settings=myapp.test_settings myapp.tests.Testclass Can anyone help. -
Django; how to show the data of two models
am working on a project where one user adds price and then confirms the booking. My point is a user1 add a post and user2 add price on user1 post so when user1 accepts the price then user2 confirm the booking. Now the question is add price model user2 and booking model user2 are same but the posting user1 now I want to show data of user2 of two models. here is the model of add price. class price(models.Model): my_post = models.ForeignKey(Loader_post, related_name='prices', on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) status = models.BooleanField(default=False) approved = models.BooleanField(default=False) vehicle_type = models.CharField(max_length=50, default='') here is my model to confirm the booking of the same user. class Booking(models.Model): post = models.ForeignKey(Loader_post, related_name='b_post', on_delete=models.CASCADE, default='', null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') approved_price = models.BooleanField(default=False) b_price = models.CharField(max_length=50, default='') vehicle_type = models.CharField(max_length=50, default='') vehicle_model = models.CharField(max_length=50, default='') this is my view class Booking_view(ListView): context_object_name = 'prices' model = price template_name = "Booking_view.html" what kind of filter should I use for that? -
Django file does not exist error when trying to attach pdf in email based on conditions
I am trying to send a 2 pdf files as attachment,1 generated by xhtml2pdf and another which is already present in the app directory of my django project, based on a condition. I am able to send the generated file and 1 file but getting error " File does not exist" for the other condition, even when both the files are in the same location. I am a newbie here, what am i doing wrong? where and how do i need to store the files to be attached ? my views code for email- patienthist = get_object_or_404(PatientHist, pk=email_id) # stores values (Y,N) pdf = Render.render('eradicate/dietplan.html', context) msg = EmailMessage("Your Diet Plan", "Attached is your diet plan!", to=[email_id]) msg.content_subtype = "html" msg.attach('my_pdf.pdf', pdf, 'application/pdf') # attaching generated pdf if patienthist.foodhabit == 'N': msg.attach_file('eradicate/LCHF Eradicate Diabetes.pdf') # doest not get attached else: msg.attach_file('eradicate/LFV Eradicate Diabetes.pdf') # gets attached to email msg.send() error i am getting- FileNotFoundError at /eradicate/test@gmail.com/dietplan/ [Errno 2] No such file or directory: 'eradicate\\LCHF Eradicate Diabetes.pdf' Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python37\lib\pathlib.py in _opener, line 1058 note: its adding an extra backslash after the app name eradicate, why does this happen? my 2 files are stored in the django app directory, same level … -
DRF: APIView.finalize_response does not work when internal error happens
I have an APIView and I have overrode finalize_response method to log some information. It works fine but the problem is that, finalize_response won't be called when an internal error happens! While server responses with 500 status and some message! How can I catch internal error and log information about response?? class MyApiView(APIView): ... def finalize_response(self, request, response, *args, **kwargs): # doing some logging stuff! -
Changing names of Django form field in clean method
I am trying to change the names of my Django form fields in the clean method, depending on whether its value is True or False after the form is submitted. However, the method appears not to be using the new fields names calculated in the top part of the method, to clean the data in the second part, as I am getting a ValueError: 'UserServices' has no field named 'temporary_life_changes_end_date', but when I put a print statement in and print the cleaned data, 'temporary_life_changes_end_date' exists as a key. Why is this? def clean(self): cleaned_data = super().clean() # Change the field names to the category's internal code for category in enums.Category: if category.value in cleaned_data: if cleaned_data[category.value] == True: internal_code = models.RecordType.objects.get( industry_code=category.value ).internal_code cleaned_data[internal_code] = cleaned_data.pop(category.value) if category.value + "_end_date" in cleaned_data: cleaned_data[internal_code + "_end_date"] = cleaned_data.pop( category.value + "_end_date" ) else: cleaned_data.pop(category.value) if cleaned_data.get( "families_with_young_children_5_or_under", False ) and not cleaned_data.get("families_with_young_children_5_or_under_end_date", False): self.add_error( "families_with_young_children_5_or_under_end_date", "Please enter a date" ) if cleaned_data.get("temporary_life_changes", False) and not cleaned_data.get( "temporary_life_changes_end_date", False ): self.add_error("temporary_life_changes_end_date", "Please enter a date") -
How to upload multiple images using a single file upload button in django forms
I have been struggling to upload multiple images using single file upload button in django forms in my blog post. I will highly appreciate any assistance especially in creating the views.py that will enable the functionality. Here is part of my code. models.py from django.db import models from django.utils.text import slugify from django.conf import settings from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver def upload_location(instance, filename, **kwargs): file_path = 'posts/{author_id}/-{filename}'.format( author_id=str(instance.author.id), filename=filename ) return file_path class Post(models.Model): title = models.TextField(max_length=100, null=False, blank=False) detail = models.TextField(max_length=500, null=False, blank=False) date_published = models.DateTimeField(auto_now=True, verbose_name='date published') date_updated = models.DateTimeField(auto_now=True, verbose_name='date updated') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.detail class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_location) def __str__(self): return self.post.detail @receiver(post_delete, sender=Post) def submission_delete(sender, instance, **kwargs): instance.image.delete(False) def pre_save_ad_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.author.username + '-' + instance.detail) pre_save.connect(pre_save_ad_post_receiver, sender=Post) forms.py from django import forms from posts.models import Post, PostImage class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['type', 'category', 'sub_category', 'detail', 'currency', 'price'] class ImageForm(forms.Form): images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = PostImage fields = ['images'] home.html <form class="post-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ posts_form }} {{ images_form … -
Django Fullcalendar Not rendering
I will get straight to the point. I'm using FullCalendar in mu application, and it's working fine, as aspected, but somehow, I have bugs when I try to render the calendar with ajax call, so the second time. When I call the landing page, the view, calendar gets rendered properly, but when I try to filter down the calendars using ajax implementation, the rendering is lost! I literally have no idea why is this happening, so any help will be great! The idea is simple, when I land on the page, I have all calendars rendered, and if I want to chose the particular calendar group, I just want to do a basic filtering depending on the users data. First, this is my function which handles the page : @login_required(login_url='registration/login') def add_event(request, pk): cal_group_param = request.GET.get('value_from_the_user', None) #Takes the users input from the frontend context = {} ... # Code which is nor relevant for this question ... events_all = Events.objects.all() if cal_group_param: calendars = Calendar.objects.all().filter( date_valid__gte=now.date(), calendar_master__group__cusopis=cal_group_param, ).order_by('date_valid') else: calendars = Calendar.objects.all().filter( date_valid__gte=now.date(), calendar_master__group__cusopis__icontains='default_group', ).order_by('date_valid') form = ZakaziForma() if request.method == 'POST': form = ZakaziForma(request.POST or None) if form.is_valid(): ... return redirect(success_page) context['cal_groups'] = cal_groups context['calendars'] = calendars context['form'] … -
how to Serve Pdf data from server to client. (Django)
I am working on a ebook reader app in which people can send pdf and get pdf content on more mobile read-friendly way. anyway to serve pdf data from server to client without disturbing images? for more info: i am using djnago rest framework. -
get_field_display() does not return string after saving it
Hereby my (simplified) situation. When I change a choicefield from one to the other, I want to record a message saying "Field changed from (previous) to (new)" In parenthesis I'd like the actual label of the field, so in case of the example below that should be "Field changed from Open to Completed". However, for some reason I am only able to generate "Field changed from Open to 2" I am baffled why this happens given that I use the exact same code. Any ideas? class Task(Record): class Status(models.IntegerChoices): OPEN = 1, "Open" COMPLETED = 2, "Completed" status = models.IntegerField(choices=Status.choices, db_index=True, default=1) Then in my views I try to do this: if request.POST["status"] == 2: description = "Status changed from " + info.get_status_display() + " → " # This works fine, returning "Status changed from Open → " info.status = request.POST.get("status_change") info.save() description = description + str(info.get_status_display()) # Yet for some reason this fails, and I end up with an integer (2)! even though I use the same syntax