Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Can i Create a UI using nested database table fields in Python Using REST API?
I want to Create a tree structure for categories and subcategories in UI. Data should be retrieve from database entries. I have to Use REST API to get the data from backend & authentication for REST API as well UI 1. Create a tree structure for categories and subcategories view. 2. Subcategories can be up to N level Database: 1. Create database and required tables for managing tree structure 2.Use test entries to display on UI Backend: 1. Write Python code to fetch and display data 2. Use Authenticated REST API as a middleware -
Is there a way of accessing other table using foreign key
I am making a job-portal and I needed to access user field of Vacancy model using VacancyApply model. model.py class Vacancy(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) jobcategory=models.IntegerField(choices=( (1,'IT/Telecomunication'), (2,'Engineering'), (3,'Medical'), )) title=models.CharField(max_length=50) date_added=models.DateTimeField(auto_now_add=True) updated_on=models.DateTimeField(auto_now=True) deadline=models.DateField(default=datetime.now() + timedelta(days=15)) description=RichTextField() def __str__(self): return(self.title) class VacancyApply(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) vacancy=models.ForeignKey(Vacancy,on_delete=models.CASCADE) applieddate=models.DateField(auto_now=True) status=models.IntegerField(choices=status_choices,default=1) -
Direct assignment to the forward side of a many-to-many set is prohibited
I'm trying to write a script that will fill database from json file. It looks like this: class Command(BaseCommand): def handle(self, *args, **options): categories = load_from_json('categories') ProductCategory.objects.all().delete() for category in categories: new_category = ProductCategory(**category) new_category.save() restaurants = load_from_json('restaurants') Restaurant.objects.all().delete() for restaurant in restaurants: category_name = restaurant['category'] _category = ProductCategory.objects.get(name=category_name) restaurant['category'] = _category new_restaurant = Restaurant(**restaurant) new_restaurant.save() When i run it, django throws an error: Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead. My models looks like this: class ProductCategory(models.Model): name = models.CharField(verbose_name='наименование категории', max_length=64, unique=True) image = models.ImageField(upload_to='category_images', blank=True) description = models.TextField(verbose_name='описание категории', blank=True) def __str__(self): return self.name class Restaurant(models.Model): name = models.CharField(verbose_name='наименование ресторана', max_length=64, unique=True) description = models.TextField(verbose_name='описание категории', blank=True) image = models.ImageField(upload_to='restaurant_images', blank=True) category = models.ManyToManyField(ProductCategory) def __str__(self): return self.name Looks like many people have encountered with this problem, but i struggle with finding a solution to this. -
save() prohibited to prevent data loss due to unsaved related object 'xxxxxxxx'
I'm trying to create a logic in Django to check if all the TabularInline items are saved before saving the model itself. here is the code am using: def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: item_count_in_origin = instance.prc_item.quantity print(item_count_in_origin) if instance.quantity > item_count_in_origin: messages.error(request, 'Quantity is higher than origin branch.') return else: for item in instances: if item.id is not None: item.close() else: formset.save() def save_model(self, request, obj, form, change): if obj.transfer_items.all().count() != 0: user = request.user if self.save_formset: if not change: obj.solicitor = user obj.date_solicited = datetime.now() created_status = Status.objects.get(name=StatusEnum.CREATED) obj.status = created_status return super(TransferenceAdmin, self).save_model(request, obj, form, change) else: messages.error(request, 'Quantity is higher than origin branch.') return when the condition if instance.quantity > item_count_in_origin: it works right and bring back an error, but when it is false and we go the part of for item in instances: if item.id is not None: item.close() else: formset.save() it fails with the error save() prohibited to prevent data loss due to unsaved related object 'xxxxxxxx'. -
Django Channels 2 implementing Multiplexer/Demultiplexer like Channels 1
Unless I am missing something it seems there is not out-of-the-box solution for multiplexing a single channel in Channels 2 like we had with Channels 1. My understanding is I effectively have 3 consumers in Channels 1 served by a single multiplexer/channel there is nothing analogous to this in Channels 2. First option is that I'd rather not touch the client code and mimic a multiplexer unless this seems wrong-headed. Other option (I think from my initial readings in Channels 2) is I'd just have 3 endpoints as websocket URL routes and change the client code to use multiple websockets using those routes. Are those both viable options? Which makes the most sense? -
How to apply __str__ method to subclass of abstract superclass class
I have 3 models, one of which is an Abstract superclass and two of which are subclasses if that superclass. I am trying to implement a simple str method on the model, but no matter the implementation it throws me this error: TypeError: __str__ returned non-string (type NoneType) Here are my models: class DemandBase(models.Model): demand = models.FloatField(blank=True, null=True) building = models.ForeignKey(Building, on_delete=models.CASCADE) class Meta: abstract = True class DemandHeat(DemandBase): def __str__(self): return str(self.id) class DemandCool(DemandBase): def __str__(self): return str(self.id) Ok so I tried casting it as in the example above, but I tried also the following without success: return "This is an example {}".format(self.demand) and this return f"This is an example {self.demand}" and this: return "this is a string" All these alternatives work on normal models, but here it doesn't, so I assume it has to do with the inheritance or the abstraction of the class..... Any help or hints are very much appreciated. Thanks in advance! -
How can I use 3D in Django 2.0
I want to use 3D in my Django project. For object presentations, animations and web design. I heard about WebGL, Blender4web, WebGL2 and many other. But which one more good if I want to use it in django. And I don't want to learn js more hard, c++ and other for that. If you need to know, I use blender and unreal engine 4 for create 3d, but i think it's not important... -
Dynamically counting objects in an aggregate Django
I have a relatively complex query to handle and I'm bashing my head against it. Allow me to explain the scenario. I want to return a queryset annotated with the number of cases a user has completed where they are certified. Imagine my user has three roles. a_delegate, b_certified and c_accredited. a_delegate tells us that the user is in training for course a, we don't want to count any completed cases for course a. b_certified tells us that the user has completed training for course b and is certified. We need to count these completed cases c_accredited tells us that the user has advanced past their training for course b. We need to count these completed cases I am using the built-in User model that Django supplies, nothing special there. Roles are just the name of the built-in Group model that Django supplies again. Now, I know this is likely to get "just write raw sql" comments, and that's fine. I'm not dismissing the possibility of using raw sql here. I just want to know if there is a way of doing this with the ORM first. I have this function, which maps input to relevant roles. def convert_filter_str(str: str) … -
How to properly fork an app in Django Oscar 2.0
I am attempting to make a minor modification to the mixin.py file in the checkout app (specifically, attempting to comment out the line within OrderPlacementMixin that automatically sends an email after a successful order as described in this stackoverflow post). However, I can't seem to get oscar to recognize my fork. I have already followed the steps as enumerated here, with no luck. Here are the steps I've done 1) Create a custom_apps directory in the project root, and an empty __init__.py file inside it 2) Run manage.py oscar_fork_app checkout custom_apps - this command generates the checkout directory as well as multiple files. Here's the terminal output. I've also attached a photo of the directory structure (venv) work@pc:~/MyProjects/oscar2_project/frobshop$ ./manage.py oscar_fork_app checkout custom_apps Creating package custom_apps/checkout Creating app config Creating models.py Replace the entry 'oscar.apps.checkout.apps.CheckoutConfig' with 'custom_apps.checkout.apps.CheckoutConfig' in INSTALLED_APPS 3) I commented out 'oscar.apps.checkout' in my INSTALLED_APPS in my settings.py, and I inserted 'custom_apps.checkout' at the end of the INSTALLED_APPS` list 4) I run python manage.py runserver, to which I get the exception oscar.core.exceptions.AppNotFoundError: Couldn't find an Oscar app to import checkout.calculators from. At this point, I haven't even tried to modify any code yet, however, my fork already refuses to … -
How to update a field of another model in a pre_save function?
I have a model called SPL, which gets new objects in a fixed interval. Everytime it gets a new object, the function "process_data" gets called by the pre_save signal. In this function, I am trying to update the field "leq_start" in another model "Index" based on the field "time" of the SPL model object. The Code seems to work because I don't get any error, but the field does not get updated. What's wrong? I have some other functions based on a post_save signal where it works fine... I've already tried the update alternative, but that didn't work either. Index.objects.filter(device_id=id_).update(leq_start=instance.time) def process_data(sender, instance, **kwargs): id_ = instance.device_id num = instance.number # new code prevNum = Index.objects.get(device_id=id_).previous_nbr dP = num - prevNum if dP > 0: if prevNum == 0: dT = 60 b = Index.objects.get(device_id=id_) b.leq_start = instance.time b.save() instance.leq_60=instance.leq return else: ... pre_save.connect(process_data, sender=SPL) -
How to realize the hard delete function in Python Django?
I have a User realization class, in there I want to have two type delete function: class User(AbstractUser): nickname = models.CharField(max_length=16, blank=True, null=True) # nickname real_name = models.CharField(max_length=12, null=True, blank=True) phone = models.CharField(max_length=18) # telephone ... status = models.CharField(max_length=1, null=True, default=1) def soft_del(self): self.status = 4 return True def hard_delete_user(self): # what should I do there? return True you see, one is soft delete a user, the other is hard delete a user. I mean the soft delete, a user still in the database, but I will not query it by my code, the hard delete is delete it from the database table. How to realize the hard_delete_user function? -
Saleor Stripe integration shows only one payment method (card) while in test mode
I enabled the Stripe implementation for Saleor. I added the correct api-keys. The connection is working. But Saleor only shows 1 of multiple payment methods provided by Stripe. I am working in testmode so I expect all payment methods to be shown. Stripe marks them also with 'testmode' in their own environment. Someone had this problem before? Can't find any documentation about this problem. -
why does my app doesn't render my Tabs in Django?
I am trying to delevop a website containing few tabs in it. I am not getting how to render it in django. Tabs doesn't changes instead it jst reload. I have tried with various ideas i could get but its not leading me anywhere. html code: <ul class="nav nav-tabs text-center" role="tablist"> <li role="presentation" class="active"><a href="#tab01" aria-controls="tab01" role="tab" data-toggle="tab">Overview</a></li> <li role="presentation"><a href="#tab02" aria-controls="tab02" role="tab" data-toggle="tab">Itinerary</a></li> <li role="presentation"><a href="#tab03" aria-controls="tab03" role="tab" data-toggle="tab">Lodging</a></li> <li role="presentation"><a href="#tab04" aria-controls="tab04" role="tab" data-toggle="tab">Faq &amp; Review</a></li> <li role="presentation"><a href="#tab05" aria-controls="tab05" role="tab" data-toggle="tab">Gallery</a></li> <li role="presentation"><a href="#tab06" aria-controls="tab06" role="tab" data-toggle="tab">Dates &amp; Price</a></li> </ul> url.py: path('a/', trip.views.tripdetail, name='tripdetail') views.py: def tripdetail(request): Menuz = Tripdetail.objects return render(request,'trip/tripdetail.html') Tabs should be active as it is clicked but its not doing. Its ok with normal in normal HTML codes But Not done in Django -
Python Data frame read json and filter data from dataframe
I have json format like this { "2015": [ { "DayofWeek": 4, "Date": "2015-02-06 00:00:00", "Year": 2015, "y": 43.2, "x": 10.397 } ], "2016": [ { "DayofWeek": 4, "Date": "2016-02-06 00:00:00", "Year": 2016, "y": 43.2, "x": 10.397, "Minute": 0 } ], "2017": [ { "DayofWeek": 4, "Date": "2017-02-06 00:00:00", "Year": 2017, "y": 43.2, "x": 10.397, "Minute": 0 } ] } I am reading JSON file like this, and after reading json file; converting it to data frame with open('sample.json') as json_data: data = json.load(json_data) df=pd.DataFrame([data]) Now, I want filter data based on certain input key value like DayofWeek and Year etc. Example: Case1: if input value is DayofWeek=4, then I want filter all objects having DayofWeek=4. Case2: if input value is both DayofWeek=4 and year=2017, then I want filter all the 2017 years data from json having DayofWeek=4. I have tried this code, but it is not working filteredVal=df['2017'] filter_v={'2015':{'DayofYear':4}} pd.Series(filter_v) -
Python Django Class Syntax Errror
I am relatively new to python and django. Trying to implement a python class but get this strange syntax error from invoice.models import Invoice from invoice.serializers import InvoiceSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class InvoiceList(APIView): def get(self, request, format=None): try: invoices = Invoice.objects.all() serializer = InvoiceSerializer(invoices, many=True) return Response(serializer.data) except Invoice.DoesNotExist: raise Http404 serializer = InvoiceSerializer(invoices, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = InvoiceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST class InvoiceDetail(APIView): def get_object(self, pk): try: return Invoice.objects.get(pk=pk) except Invoice.DoesNotExist: raise Http404 def get(self, request, pk, format=None): invoice=self.get_object(pk) serializer=InvoiceSerializer(invoice) return Response(serializer.data) def put(self, request, pk, format=None): invoice=self.get_object(pk) serializer=InvoiceSerializer(invoice, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): invoice=self.get_object(pk) invoice.delete() return Response(status=status.HTTP_204_NO_CONTENT) this is error I get. I don't understand why it's giving me this error because error seems right to me class InvoiceDetail(APIView): ^ SyntaxError: invalid syntax -
Where to make a loop in templates(index.html) of django?
There are two div for two columns. I want to make a loop in it so that I don't have to repeat. I tried a loop above the section tag then after section tag but it is not working. Instead it shows the picture twice. {% static 'images/fulls' as baseUrl %} {% static 'images/thumbs' as hiUrl %} <section class="thumbnails"> {% for dest in dests %} <div> <a href="{{baseUrl}}/{{dest.img}}"> <img src="{{hiUrl}}/{{dest.img}}" alt="" /> <h3>how are you</h3> </a> </div> <div> <a href="{{baseUrl}}/{{dest.img}}"> <img src="{{hiUrl}}/{{dest.img}}" alt="" /> <h3>Lorem ipsum dolor sit amet</h3> </a> </div> {% endfor %} </section> -
Sort through linked model with ForeignKey
I need to do a sorting of the Credit records through the associated models of CreditPayment. models.py class Credit(models.Model): hot = models.BooleanField(default=False) class CreditPayment(models.Model): credit = models.ForeignKey(Credit) period_to = models.PositiveIntegerField() rate = models.DecimalField(max_digits=7, decimal_places=2) views.py credits = credits.filter(hot=False).distinct().order_by(...) Example of input data: Credit #1: CreditPayment #1: period_to = 12 rate = 10 CreditPayment #2: (minimal) period_to = 10 rate = 8 CreditPayment #3: period_to = 9 rate = 10 Credit #2: CreditPayment #1: (minimal) period_to = 6 rate = 20 CreditPayment #2: period_to = 9 rate = 20 Credit #3: CreditPayment #1: period_to = 12 rate = 8 CreditPayment #2: period_to = 9 rate = 11 CreditPayment #3: (minimal) period_to = 9 rate = 8 As a result, the sample is reduced to: Credit #1: CreditPayment #2: period_to = 10 rate = 8 Credit #2: CreditPayment #1: period_to = 6 rate = 20 Credit #3: CreditPayment #3: period_to = 9 rate = 8 Result: Credit #3 -> Credit #1 -> Credit #2 As you can see, at first the minimum CreditPayment was selected for each Credit (credits at views.py). Then, according to these minimum CreditPayment, allCredit is sorted. If the rate of two or more entries are equal, compare byperiod_to. … -
django: Localhost stopped working suddenly?
I'm truing to run a django server and all of a sudden I'm not able to go to localhost:8000. I was able to a few seconds back, but now now it's just freezing up and saying "waiting for localhost" How do I debug this? -
Sending files as an attachment Django
I have created an XLS file and want to send it as an attachment to an email. The following code is working fine and I receive an email with the XLS file (status code is 200 OK). # This is working code import xlwt import StringIO import zipfile from django.core.mail import EmailMessage work_book = xlwt.Workbook() # Here some boring stuff with excel ... report_name = "do_something_%(username)s_%(current_date)s.xls" f = StringIO.StringIO() work_book.save(f) message = EmailMessage( subject=u"Sample Title", body=u"Sample body", to=["test@company.com"]) message.attach(report_name, f.getvalue()) message.send() But if I try to send compressed XLS file (using zipfile), i don't receive anything (However status code is "200 OK"). I replaced the last 2 lines of code with the following: report_name_zip = 'do_something_%(username)s_%(current_date)s.zip' with zipfile.ZipFile(f, mode='w', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(zinfo_or_arcname=report_name, bytes=f.getvalue()) message.attach(report_name_zip, f.getvalue()) message.send() -
Django serialize one field only instead of whole model in related fields (readonly)
I'd like to serialize a nested model field that only has one field by using the field of the nested model directly. Following code should explain the situation: # models class Tag(models.Model): title = models.CharField(max_length=255, unique=True) class Scene(models.Model): title = models.CharField(max_length=255, unique=True) tags = models.ManyToManyField(Tag, blank=True) # serializers class SceneSerializer(serializers.ModelSerializer): class Meta: model = Scene fields = ('id', 'title', 'tags',) read_only_fields = ('tags',) which outputs the following if used: { "id": 1, "title": "yolol", "tags": [ 1, 2 ] } What I'd like to have is the following output (using Tag.title instead of the primary key): { "id": 1, "title": "A Scene", "tags": [ "3D", "Industry" ] } How do I write a serializer that does this for the tags? -
Manager isn't available; Game is abstract
When i try to save i got this error. Manager isn't available; Game is abstract I tried a few methods I found, but it didn't work; like objects=models.Manager() When i delete objects=models.Manager() i got this error type object 'Game' has no attribute 'objects' my models.py class Game(models.Model): name=models.CharField(max_length=255,blank=True,null=True) slug=models.SlugField(unique=True,max_length=255) match=models.ManyToManyField(Match) objects=models.Manager() def get_unique_slug(self): slug=slugify(self.name.replace('ı','i')) unique_slug=slug counter=1 while Game.objects.filter(slug=unique_slug).exists(): unique_slug='{}-{}'.format(slug,counter) counter+=1 return slug def save(self,*args,**kwargs): self.slug=self.get_unique_slug() return super(Game,self).save(*args,**kwargs) class Meta: abstract = True class LeagueOfLegendsGame(Game): team1player=models.ManyToManyField(Player,related_name='team1player') team2player=models.ManyToManyField(Player,related_name='team2player') -
How to integrate django-pesapal to a subscription site
I am trying to add the process payment function on https://django-pesapal.readthedocs.io/en/latest/ to my signup views for new users to subscribe. How do I go about that and which URL should the signup form have? -
Django Cities Light not populating DB
I'm using django cities light for my app, the first time I installed it and configured it, it worked perfectly. But now after deleting and making changes to my code when I run the commands of Django cities light no data is populated. Though I used the same command an hour ao and it worked perfectly fine. I tried using the force command and all the other options but no results. Here is the link to the lib Django cities light -
relation "background_task" does not exist
I'm trying to run some tasks in the background while running a django server. To do this, I'm using background-tasks library. I've followed the following steps: pip install django-background-tasks Wrote 'background_task', in INSTALLED_APPS in settings.py python manage.py makemigrations background_task the problem arises in the 3rd step giving an error stating: django.db.utils.ProgrammingError: relation "background_task" does not exist LINE 1: INSERT INTO "background_task" ("task_name", "task_params", "... I've tried looking for other solutions but every one of them was the 3rd line. How should I proceed? -
How can I generate Allure report files when working with Django and manage.py test runner?
I have a Django project and I usually run the unit tests with the command: manage.py test I have installed allure-pytest but I don't know how to use it. The documentation is about using pytest, but I don't use pytest to run my tests. Does anyone know how I should run my Django tests and make them generate allure report files, when I use the manage.py test command to run them?