Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make django post accept str rather than pk
I have relational DB and a file info to post in it. DB provides 3 entities holding ForeignKey in some attributes. Entities are: File, WorkFile and WorkFileStage. My issue is, when I post info of specific file, I must post on those endpoints, but e.g. WorkFile holds attribute file = ForeignKey(File) - it's an id filed. Which makes me POST all the File data, then GET it for acquring IDs, then POST on WorkFile with those IDs. THIS IS A LOT OF POSTINGGETINGITERATINGANDPROMISING (as my request are done with axios on react). What I've tried, is for POST data construct object with just a file=file_name, then search it in the DB on the django side and serialize.save(). But POST requiers pk rather than str for foreignKeys. With this though process I ended up with axios.post().then(axios.get().then(axios.post(then)))). Is there any easy/good practice way of doing it? -
ERROR : Microsoft Visual c++ 14.0 required, thrown while pip installing Numpy
While pip installing numpy version 1.19.2 (via pycharm) below error is thrown ERROR : Microsoft Visual c++ 14.0 required I have tried the workarounds given in the sites nothing seems to be working -
Django, views, when I import the model it won't take the method "objects"
I have done the makemigrations and the migrate and I see the tables created in postgresql, but the function in the view will not pick the .objects(all) method This is one snippet of the models class Donor(models.Model): thename = models.CharField(max_length=30, unique=False) city = models.CharField(max_length=30, unique=False) VIEWS from django.shortcuts import render from .models import Donor Create your views here. def index(request): list = Donor.objects.all() #The word objects gets highlighted bc it is not accepted as method return render(request, 'home.html', {'lista':thelist}) UPDATE: The refreshingg of the page won't happen will give error -
Getting data from Django website after logging in with requests
I have logged with user credentials using the following code: import requests url_login='https://test.com/admin/' user = 'test' password = 'test' headers = { # 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0', # 'Accept': 'application/json, text/javascript, */*; q=0.01', # 'X-Requested-With': 'XMLHttpRequest', # AJAX 'Referer': 'https://test.com/admin/login/?next=/admin/', } client = requests.session() client.get(url_login) csrftoken = client.cookies['csrftoken'] login_data = {'username':user,'password':password, 'csrfmiddlewaretoken':csrftoken, 'next': '/pecasRunLog/'} print(login_data) r1=client.post(url_login,data=login_data, headers=headers) r1.status code returns 200 which seems to be fine. But how can I proceed with fetching data from the pages available only for logged in users with requests. Tried this and that and it still returns log in page. -
Django unable to access files after deployment
So I am currently working on a Sudoku Solver that takes an image input from the user splits it into 81 boxes which are read separately to reconstruct a 2d array of the sudoku to then be solved. These numbers are stored in a directory called '/81/' which I defined in the settings.py as NUM_DATA. Everything works fine in the dockerized and plain Django runserver command, however, after hosting it shows an error: OpenCV(4.5.1) /tmp/pip-req-build-ms668fyv/opencv/modules/imgproc/src/resize.cpp:4051: error: (-215:Assertion failed) !ssize.empty() in function 'resize' most probably because it isn't able to access that '/81/' directory or the file is empty. Now I know it isn't a good practice to upload the entire website and github link, but I really can't seem to track down the issue with the code. Website: https://supersudokusolver.herokuapp.com/ Github code: https://github.com/psymbio/sudoku-solver-v1 Also, should I try deploying it somewhere else? -
Sorting a queryset in for loop in a Django template not working
I'm having a problem with django's for loop template tag not sorted. {% for profile in profiles|sort_list:filter_args %} my code here {% endfor %} 'profiles' is a list of dictionaries, and I'm trying to sort the list based on a chosen sort option from input on the page. <select name="sort" id="sort" onchange="sort();"> <option value="username">username</option> <option value="age">age</option> <option value="height">height</option> </select> The logic I used follows the steps. Anually change the sorting option like sort by username or sort by age, etc.. Javascript detects the onchange event and send a request to the server using Ajax. The server returns the sort and reverse options like filter_args = {'sort_by': 'username', 'up_down': 'up'} 'filter_args' goes into a custom template tag filter defined as def sort_list(profiles, filter_args): sort_by = filter_args["sort_by"] up_down = filter_args["up_down"] if up_down == "down": profiles = sorted(profiles, key=lambda i: i[sort_by], reverse=True) else: profiles = sorted(profiles, key=lambda i: i[sort_by]) return profiles Then, I should see that the profiles list is sorted. And HTML elements in the for loop should sorted too. {% for profile in profiles|sort_list:filter_args %} my code here {% endfor %} I also made sure that the custom template tag works fine (put print() in the function). def sort_list(profiles, filter_args): sort_by … -
Django wagtail {% slug url '<page>' %} page not found heroku
I have a small site made in Django (3.1.5) with Wagtail (2.11.3) and python 3.8.5 I am having a problem with my links when deploying my site to heroku. It is only a small portfolio site, so there are only 6 direct links to manage in the navbar. These page links work fine when ran on localhost, but I'm not sure what is happening when I deploy to heroku. The links I use utilise 'slugurl' e.g: <li class="menu-item"> <a href="{% slugurl 'about' %}">About</a> </li> <li class="menu-item"> <a href="{% slugurl 'resume' %}">Resume</a> </li> <li class="menu-item"> <a href="{% slugurl 'projects' %}">Projects</a> </li> <li class="menu-item"> <a href="{% slugurl 'blog' %}">Blog</a> </li> <li class="menu-item"> <a href="{% slugurl 'contact' %}">Contact</a> </li> In the wagtail admin, I make sure that the slug matches the slugurl in the links e.g resume: Also, when I go to the slug e.g mysite.com/resume the page loads fine and everything on it, statics, templates and added content through wagtail admin, etc works fine with no problems. However, when I click on the navbar which has href = {% slugurl 'resume' %} in the navbar raw HTML as above, I get a 404 error with the following in the address bar: mysite.com/None/ … -
Rest API call returning forbidden
I am trying to get some data by calling a rest API but it's not working and returning: Forbidden: /api/networthchart/data/ My view/API call: (Please ignore the print functions, I was using those for testing, but I left them in here just in case) class networthChart(APIView, View): authentication_classes = [] permission_classes = [] def get(self, request, format=None): print("its working") labels = [] default_items = [] if not self.request.user.is_active: return HttpResponseForbidden("Not signed in") # any error you want to display else: print("user signed in") user = self.request.user networth_history = user.networthTracker.objects.filter(user = user) queryset = networth_history.order_by("date") print("questset gotten") for query in queryset: default_items.append(query.networth) labels.append(query.date) print("adding") print(labels) print(default_items) data = { "labels" : labels, "default" : default_items, } return Response(data) and the JS is: <script> $(document).ready(function(){ var endpoint = '/api/networthchart/data/' var defaultData = [] var labels = [] $.ajax({ method:"GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of Votes', data: defaultData, #there was other stuff in here like bg colour and but I removed it for the sake of saving your time. }); }, error: function(errordata){ console.log(errordata) } }) } }) … -
Django Admin template how get specified value in fieldset
Im overwiting view "admin/includes/fieldset I want to do conditional rendering: if My template: <fieldset class="module aligned {{ fieldset.classes }}"> {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %} {% if fieldset.description %} <div class="description">{{ fieldset.description|safe }}</div> {% endif %} {% for line in fieldset %} <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} {% for field in line %} <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} {% if field.is_checkbox %} {{ field.field }}{{ field.label_tag }} {% else %} {{ field.label_tag }} {% if field.is_readonly %} <div class="readonly">{{ field.contents }}</div> {% else %} {% if field.field.name == 'car' %} {% if fieldset['date'].field.value > '2012-10-10'} Attetion: {% endif %} {% endif %} {{ field.field }} {% endif %} {% endif %} {% if field.field.help_text %} <div class="help">{{ field.field.help_text|safe }}</div> {% endif … -
Key error in django rest framework in VideoPostSerializer
I am trying to add some functionality to the create API handler to upload multiple files but unable to to do . I am getting KeyError at /api/posts/post/video/ 'video' while trying to post through POSTMAN POSTMAN error any suggestions will be much appreciated my models. py # Video Post class VideoPost(models.Model): user = models.ForeignKey("profiles.HNUsers", on_delete=models.DO_NOTHING) timestamp = models.DateTimeField("Timestamp", blank=True, null=True, auto_now_add=True) text = models.TextField("Description text", blank=True) class Meta: verbose_name_plural = "Video Posts" class PostVideo(models.Model): video_post = models.ForeignKey('VideoPost', models.CASCADE, related_name='post_video') video = models.FileField("Post Video", blank=True, null=True) my serializers.py # VideoPostSerializer class PostVideoSerializer(serializers.ModelSerializer): class Meta: model = PostVideo fields = '__all__' class VideoPostSerializer(serializers.ModelSerializer): post_video = PostVideoSerializer(many=True, required=False) def create(self, validated_data): videos = validated_data.pop('post_video') post = VideoPost.objects.create() if videos: videos_instance = [PostVideo(post=post, video=video) for video in videos] PostVideo.objects.bulk_create(videos_instance) return post class Meta: model = VideoPost fields = ( 'user', 'text', 'post_video', ) my views.py # video post starts here @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def video_post(request): if request.method == 'POST': data = request.data print(data) serializer = VideoPostSerializer(data=data) if serializer.is_valid(): serializer.save() print("video object saved") try: video_post_object = VideoPost.objects.filter(user__id=data['user']).order_by('-timestamp')[0] print(video_post_object) try: post = Posts() post.user = HNUsers.objects.get(id=data['user']) post.video_url = video_post_object.video.url post.type = 'V' post.category = data['category'] post.created_on = video_post_object.timestamp post.text = video_post_object.text save_post = post.save() post_id = post.pk … -
How to add field to form securely hidden
I have a form that when submitted, it saves some data and one of these fields is a foreign key for user id. I want to pass this request.user.id value without it showing in the HTML code (I dont want people to change it in from the inspect because of security reasons). This is the HTML: <form method="POST" action=""> {% csrf_token %} <div class="container-fluid my-3"> <div class="row justify-content-center"> {% for field in form %} <div class="{% if forloop.counter0 == 0 %} col-2 {% else %} col-1 {% endif %}"> {{ field }} </div> {% endfor %} <div class="col-1"> <input class="btn btn-primary" type="submit" display="inline" id='test'> </div> </div> </div> This is the model: class SaleEntry(models.Model): date = models.DateField() ebay_price = models.FloatField() amazon_price = models.FloatField() ebay_tax = models.FloatField() paypal_tax = models.FloatField() tm_fee = models.FloatField(default=0.3) promoted = models.FloatField(default=0.0) profit = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE) This is the form: class SaleEntryForm(ModelForm): class Meta: model = SaleEntry fields = [ 'date', 'ebay_price', 'amazon_price', 'ebay_tax', 'paypal_tax', 'tm_fee', 'promoted', 'profit' ] widgets = { 'date': DateInput(attrs={'class': 'form-control'}), 'ebay_price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'eBay Price', 'id':'f_ebay_price', 'onchange': 'calc_profit()'}), 'amazon_price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Amazon Price', 'id':'f_amazon_price', 'onchange': 'calc_profit()'}), 'ebay_tax': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'eBay Tax', 'id':'f_ebay_tax', 'onchange': 'calc_profit()'}), 'paypal_tax': forms.NumberInput(attrs={'class': … -
Django model Field default=None useful?
In my current projekt I'm working on we use default=None on model Fields, for models.CharField( sometimes default=''. Does this make any sense? I looked into the django documentation, but couldnt find an answer. I searched the django source code and for models Field the initial is set to default=NOT_PROVIDED and this is defined as class NOT_PROVIDED: pass so I'm even more confused now. Running my tests in the django project I had the feeling, that it does not really matter if I used default=None or default='' -
Python bottle serving same output to all different users
I am working on a bottle project the code is downloading videos from any website.the downloading process is ok but the problem is when two user use my website with two different video url the server downloads the files but if returning the fastly download i mean that which video download fast the code returning that video to all users. This is a problem because when two users use my website to download to different videos they must need the same video as they give the url. So please help me to separate all users. So I need like, for every user my server will return the video for which they paste the url. I used threading server paste. Please help me to find out how can i do that. from bottle import route, run,request,static_file import os try: import youtube_dl except: os.system('pip install youtube_dl') import youtube_dl x=[] def cvtmp3(filename): p=filename.split('.') print(p) a=p[0] audio=a+'.mp3' os.rename(filename,audio) print(audio) def download(url): global filename # url=input('type the valid url: ') ydl_opts = {'format': 'bestaudio/best'} os.chdir('/storage/emulated/0/') with youtube_dl.YoutubeDL(ydl_opts) as ydl: #p=ydl.extract_info('https://www.youtube.com/watch?v=n06H7OcPd-g') #print(p) info = ydl.extract_info(url, download=True) filename = ydl.prepare_filename(info) #ydl.download(['https://www.youtube.com/watch?v=n06H7OcPd-g']) @route('/') def index(): return ''' <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .loader { … -
How to remove Celery Task results from Django Admin in production
I am currently working with Django Celery and I have integrated Django celery backend for managing my background tasks. I want to remove Task Results tab from CELERY RESULTS section but could not find any help online. Image for reference: Any help would be highly appreciated :) -
How to fix UnicodeDecode error in django in this scenario?
I want to order the model objects in descending order, how am I supposed to go about doing that using the field number in my model class. Here is my views.py class SeasonDetailView(DetailView): model = CartoonSeason template_name = "episode_list.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["episodes"] = Episode.objects.filter(season=self.object) return context class EpisodeDetailView(DetailView): model = Episode template_name = "episode.html" And this is my models.py class Episode(models.Model): season = models.ForeignKey(CartoonSeason, on_delete=models.CASCADE) number = models.IntegerField() cover = models.URLField(max_length=300, blank=True, null=True) name = models.CharField(max_length=200, blank=True, null=True) description = models.TextField(blank=True, null=False) link = models.URLField(max_length=300, blank=True, null=True) published = models.DateField(auto_now_add=True, blank=True, null=True) -
Django UniqueConstraint case insensitive and unaccented
I know I could get unique case insensitive field by using from django.contrib.postgres.fields import CICharField, but I couldn't get it work by something like class Meta: constraints = [ models.UniqueConstraint( fields=["name__unaccent"], name="unique name", ), ] I have UnaccentExtension, but this still throws error django.core.exceptions.FieldDoesNotExist: Group has no field named 'name__unaccent' Am I doing something wrong? Is it somehow possible achieve, what I am looking for? -
Reverse for 'hobbieswithCSS.html' not found. 'hobbieswithCSS.html' is not a valid view function or pattern name
I am trying to attach hobbieswithCSS.html file to my website, while using Django. I am a beginner when it comes to Django, so I have naturally came across some problems (in the title) like this. I have this anchor tag on my homepage - <a href="{% url 'basic_app:hobbieswithCSS.html' %}">My Hobbies</a> I have this view in my views.py file - def hobbieswithCSS(request): return render(request,'basic_app/hobbieswithCSS.html') I think, that the main problem will be with the urlpatterns in urls.py file, because I am not sure how to set it up. These are my urlpatterns - urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), url(r'^basic_app/',include('basic_app.urls')), url(r'^logout/$',views.user_logout,name='logout'), url(r'^$', views.hobbieswithCSS, name='hobbieswithCSS'), ] Could anybody please tell me, how could I change the code in order to make that hobbieswithCSS.html file display, when I am trying to run it on my server? Thank You very much for any help. -
Django Subtract a field from another field in another table and save the result
class prodect(models.Model): name = models.CharField(max_length=50) cwan = models.DecimalField(max_digits=5, decimal_places=2) class orders(models.Model): names = models.CharField(max_length=50) prodects = models.ForeignKey(prodect,on_delete=models.CASCADE) count = models.DecimalField(max_digits=7, decimal_places=2) I have two models the first have a int field and The second is a int and I Want After the user enters a value in the second field, it is subtracted from the first, and the result of the first changes to its old result minus the value that the user entered in the second -
Django group by Choice Field and COUNT Zeros
consider the following django model: class Image(models.Model): image_filename = models.CharField(max_length=50) class Rating(models.Model): DIMENSIONS = [ ('happy', 'happiness'), ('competence', 'competence'), ('warm_sincere', 'warm/sincere'), ] rating_value = models.IntegerField(), rating_dimension = models.CharField(max_length=50, choices=DIMENSIONS), image = models.ForeignKey(Image, on_delete=models.CASCADE) Now, I'd like to group all Ratings by the number of ratings per category like this Rating.objects.values("rating_dimension").annotate(num_ratings=Count("rating_value")) which returns a QuerySets like this: [{'rating_dimension': 'happy', 'num_ratings': 2}, {'rating_dimension': 'competence', 'num_ratings': 5}] Is there a way to include all not-rated dimensions? To achieve an output like [{'rating_dimension': 'happy', 'num_ratings': 2}, {'rating_dimension': 'competence', 'num_ratings': 5}, {'rating_dimension': 'warm_sincere', 'num_ratings': 0}] # ← zero occurrences should be included Thanks in advance! -
Can not make SerializerMethodField() work
So I have this view, I passed the request through the context to the serializer so I can use it to get the user def create(self, request, *args, **kwargs): """ Handle member creation from invitation code. """ serializer = AddMemberSerializer( data=request.data, context={'circle': self.circle, 'request': request} ) serializer.is_valid(raise_exception=True) member = serializer.save() data = self.get_serializer(member).data return Response(data, status=status.HTTP_201_CREATED) In the serializer I did this but it does not work,I get "KeyError: 'user'", I ran a debugger and when I tried to call the get_user method it says "TypeError: get_user() missing 1 required positional argument: 'obj'" user = serializers.SerializerMethodField() def get_user(self, obj): request = self.context.get('request', None) if request: return request.user So what am I missing? I looked up other implementations of this field and none of them seem very different of mine, so I would really apreciate it if someone explains to me why it is not working. Also if there is a more efective way to get the user into a field (Need it to run a user_validate method on it) -
Django rest framework saving seralizer with foregin key
Quick question I am trying to save model and have following setup models.py class Example1(models.Model): field1 = models.CharField(max_length=90, null=True, blank=True) class Example2(models.Model): field2 = models.CharField(max_length=90, null=True, blank=True) example1 = models.ForeignKey(Example1, on_delete=models.CASCADE, related_name='example1_example2') serializers.py class Example1Serializer(serializers.ModelSerializer): def create(self, validated_data): return Example1.objects.create(**validated_data) class Meta: model = Example1 fields = ['id', 'field1'] class Example2Serializer(serializers.ModelSerializer): def create(self, validated_data): return Example2.objects.create(**validated_data) class Meta: model = Example2 fields = ['id', 'example1', 'field2'] upon initiating following code new_example1 = Example1Serializer(data=JSONEXAMPLE1DATA) if new_example1.is_valid(): new_example1.save() **works well** JSONEXAMPLE2DATA = { 'field2' = 'test', 'example1' = new_example1.data['id'] } new_example2 = Example2Serializer(data=JSONEXAMPLE2DATA) if new_example2.is_valid(): new_example2.save() **doesnt work gives must be a "Example1" instance** upon changing JSONEXAMPLE2DATA to JSONEXAMPLE2DATA = { 'field2' = 'test', 'example1' = new_example1 } gives Incorrect type. Expected pk value, received Example1Serializer. is setup wrong? -
Python/Django - How to set default value in custom form?
I've got form in Django: class NewsletterForm(forms.Form): first_name=forms.CharField(max_length=50,required=True,label='Twoje imię:') email=forms.EmailField(required=True,label='Twój email:') Now there is logic part: def subscribe2newsletter(request): if request.method == 'POST': form = NewsletterForm(request.POST) if form.is_valid(): cd = form.cleaned_data else: form = NewsletterForm() categories = get_categories_with_subcategories() return render(request, 'subscribe2newsletter.html', { 'form': form, 'sent': sent, 'categories': categories } ) And view part: <form method="post"> {# {{ form.as_p }}#} {% csrf_token %} <div> {{ form.first_name.errors }} <label for="{{ form.first_name.id_for_label }}">Twoje imię:</label> {{ form.first_name }} </div> <br><br> <div> {{ form.email.errors }} <label for="{{ form.email.id_for_label }}">Adres email:</label> {{ form.email }} </div> <input type="submit" value="Zatwierdź"/> </form> My problem is - how to set default value for form from logic part? I've tested construction like: form = NewsletterForm() form.first_name='some value' but it doesn't work. Input field on view is still empty. How to fill it inside subscribe2newsletter function? -
Django How to make table with attributes?
I created a system with Django. This system has a limiting system. I have several ranks and several risks. According to the these ranks and risks there are some credit values. For example: example table Users can add/update these limits (10$, 9$ ... ) For better user experience I want to create a detailed table like this: my table How can I fill cells with the format that I want? models.py class DoaTable(models.Model): LIMITS =( ('Low Risk', 'Low Risk'), ('Medium Risk', 'Medium Risk'), ('Moderately High Risk','Moderately High Risk'), ('High Risk', 'High Risk'), ('Very High Risk', 'Very High Risk'), ('Strict Credit Check', 'Strict Credit Check'), ('No Credit Check', 'No Credit Check'), ) RANKS = ( ('Analyst', 'Analyst'), ('Senior Analyst', 'Senior Analyst'), ('Lead', 'Lead'), ('Manager', 'Manager'), ('Senior Manager', 'Senior Manager'), ('Director', 'Director'), ('Regional Director', 'Regional Director'), ('Chief Financial Officer', 'Chief Financial Officer'), ) rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) limit = models.FloatField() comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) def __str__(self): return self.rank table.html <table class="table table-bordered"> <thead> <tr> <th> </th> <th>Low Risk</th> <th>Medium Risk</th> <th>Moderately High Risk</th> <th>High Risk</th> <th>Very High Risk</th> <th>Strict Credit Check(CIA/LC)</th> <th>No Credit Check</th> </tr> </thead> <tbody> <tr> <th scope="row">Analyst</th> </tr> <tr> <th scope="row">Senior Analyst</th> </tr> <tr> … -
How to use multiple databases for unit test cases in django pytest
I have been working on a django application which uses multiples databases through database router like the following. I want to write unit test cases for the apis developed using Django Rest Framework. class MultiDbRouter(object): """ Router for handling multiple database connections based on the db configs in the request object """ def _multi_db(self): if hasattr(request_cfg, 'db'): if request_cfg.db in settings.DATABASES: return request_cfg.db else: raise Http404 else: return 'default' def db_for_read(self, model, **hints): """ Set database for reading based on request config """ if model._meta.app_label == 'survey': return 'survey' if model._meta.app_label != 'analytics': return 'default' return self._multi_db() def db_for_write(self, model, **hints): """ Set database for writing based on request config """ if model._meta.app_label == 'survey': return 'survey' if model._meta.app_label != 'analytics': return 'default' return self._multi_db() def allow_relation(self, obj1, obj2, **hints): """ allow relation between objects """ return True def allow_syncdb(self, db, model): """ allow syncing of database """ return True I have started using pytest for writing the testcases, but as I read the docs of pytest-django library, it says that "Currently pytest-django does not specifically support Django’s multi-database support." Is there any way to workaround this limitation? Or should I use some other library other than pytest-django to write … -
How to get list of only one object in django
I have a model class OrderEntries(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() I need to get list of Product that is saved in this model OrderEntries.objects.all() This queryset gives me all the OrderEntries but how can I get list of all the product objects that is saved inside OrderEntries