Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django serializer ManyToMany and return name instead of id
My models: class Category(models.Model): name = models.Charfield().. code = models.Charfield()... class Movie(models.Model): name = models.Charfield().. categories = models.ManyToManyField(Category) My serializer class MovieSerializer(serializers.ModelSerialier): class Meta: model= Movie fields = ['name', 'categories', ] When i get a Movie by id it returns: [ {"name": "My Movie", "categories": [1, 2, 3], } ] I want my response to be : .... "categories": ["Fun", "Adventure", ...] -
How to display Historical table of django-simple-history in django admin site?
I have implemented Historical tracking of changes to objects in django using django-simple-history https://django-simple-history.readthedocs.io/en/2.10.0/index.html I have mentioned a field history in Model using which I can query an object's history. history = HistoricalRecords() There us also a table created in the database with name appname_historicalmodelname. I want to display this table appname_historicalmodelname in django admin where in we have list of records sorted by history_time. As I don't have a Model class for that History table, I'm unable to use admin.site.register(HistoricalModelName). Please help me display this table in django admin site. django: 1.11 python: 2.7 -
Maps java script API to Django project
I am creating a real estate web platform with Django and postgresql back-end. I have implemented maps API in my HTML template in order to show where the real estate is located. The code: <!--Map--> <div class="row mb-5"> <div class="col-md-12"> <style> #map{ height:250px; width: 100%; } </style> <div id="map"></div> <script> function initMap(){ var myLatLng = {lat:-33.90, lng:151.16}; var options = { zoom:10, center:myLatLng }; var map = new google.maps.Map(document.getElementById('map'),options); } </script> </div> </div> Markers will be added in the next step because I have to figure out how I can retrieve my LAT and LNG values from the database and display them inside the script. Does anyone have the answer? To explain that a bit further, I want to make something like <script> function initMap(){ var myLatLng = {lat:{{listing.geo_lat}}, {{listing.geo_lng}}}; var options = { zoom:10, center:myLatLng }; But I have tried that and it seems that either google api cant read the proper format of my values or listing.geo_lat is not properly working inside the script. -
Django: drop duplicated lines from Queryset after joining two models
I would like to create a table with [for loop] function from a Queryset in my html templates. There are two models as shown in the codes below. After joining two models with select_related, there will be duplicated lines, and I would like to find the line with the latest date. I have tried Order.objects.all().select_related('inspection'), but I couldn't find a way how I can remove the duplicated lines and aggregate the order num field by ', '.join function. Can you please help me to find a script that creates the [output_queryset] as shown below? Python 3.8 Django 3.0 models.py class Inspection(models.Model): RESULT_CHOICES = ( ('Passed', 'Passed'), ('Failed', 'Failed') ) inspection_id = models.CharField(max_length=30, primary_key=True) result = models.CharField(max_length=50, null=True, blank=True, choices=RESULT_CHOICES) class Order(models.Model): inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE) ordernum = models.CharField(max_length=50) departure_date = models.DateField(auto_now=False, null=True, blank=True) Example dataset inspection_list = [{'inspection_id': 'BN123', 'result': 'Passed'}] order_list = [ {'id': 1, 'inspection_id': 'BN123', 'ordernum': 'S1', 'departure_date': '2020-07-01'}, {'id': 2, 'inspection_id': 'BN123', 'ordernum': 'S2', 'departure_date': '2020-06-01'}, {'id': 3, 'inspection_id': 'BN123', 'ordernum': 'S3', 'departure_date': '2020-06-25'} ] output_queryset = [ {'inspection_id': 'BN123', 'departure_date': '2020-06-01', 'result': 'Passed', 'ordernum': 'S1, S2, S3'} ] -
Django: Two relationships between two models
I'm struggling with the creation of two models which have two relationships. My goal is that a person can own multiple objects, and always has a favorite object (which they own). So to be precise the constrains could be summed up like this: 1:n relationship Person - Object (a person [exclusively] owns multiple objects) n:1 relationship Person - Object (favorite object, every person has ONE favorite object) person.(favorite object).owner = person (a person must own their favorite object, that makes the n:1 relationship of the favorite object more like an "optional 1:1 from the object's perspective") class Person(models.Model): favorite_object = models.ForeignKey('Object') class Object(models.Model): owner = models.ForeignKey(Person) First of all, I get an error stating that I should add a related_name to help solve the reverse reference and I wonder what is the best thing to do here since the favorite relationship is optional from an object's perspective. Do I alter owner to be owner = models.ForeignKey(Person, related_name="+") to avoid the reverse reference in the first place? Secondly, how do I create objects in the first place? They depend on each other. I cannot create a user without having a favorite object and I cannot create an object without knowing its … -
how to filter value in django where 0<a<10
Guys i am filtering in django values from db.I want to filter for condition 0<a<10. i tried the following way: School.objects.filter(a__lt=10 , a__gt=0) but this option is not effictive and brings wrong results. Any idea how to make it efficient way ? Any help is appreciated -
Django-ckeditor 404 errors
I'm receiving several 404-errors when using django-ckeditor. This is what my static folder looks like The first is on the ckeditor.js file, which is located at static/boot/ckeditor/ckeditor and the error I receive is as follows: "GET /static/ckeditor.js HTTP/1.1" 404 1657 Following, I receive a few errors on other documents that are actually in the folders where I get an error: "GET .../AGAPE/static/boot/ckeditor/ckeditor/config.js?t=JB9C HTTP/1.1" 404 2494 "GET .../AGAPE/static/boot/ckeditor/ckeditor/skins/moono-lisa/editor.css?t=JB9C HTTP/1.1" 404 2548 "GET .../AGAPE/static/boot/ckeditor/ckeditor/lang/nl.js?t=JB9C HTTP/1.1" 404 2497 For the last three, I imagine that the error is caused by the characters that are added at the end of the file name, e.g. ?t=JB9C, but I don't get why these characters are added. Additionally, my settings.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/boot/') STATIC_FILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'boot'),] MEDIA_ROOT=os.path.join(os.path.dirname(BASE_DIR), 'media') MEDIA_URL="/media/" CKEDITOR_BASEPATH = os.path.join(os.path.dirname(STATIC_ROOT), 'ckeditor/ckeditor/') CKEDITOR_UPLOAD_PATH = "uploads/" CKEDIT_IMAGE_BACKEND = 'pillow' CKEDITOR_CONFIGS = { 'default': { 'toolbar':[ ['CodeSnippet', ], ], 'height': 400, 'width': 900, 'removePlugins': 'stylesheetparser', 'extraPlugins': 'codesnippet', }, } And the relevant models.py file (in the relevant app): from django.db import models from django.contrib.auth.models import User from ckeditor_uploader.fields import RichTextUploadingField from ckeditor.fields import RichTextField STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) cover = models.ImageField(upload_to='images/') … -
when im trying to add questions in the Question model with choices from Choice model it is showing all the choices from previous additions ,
when im trying to add questions in the Question model with choices from Choice model it is showing all the choices from previous additions ,but i want different choices for each here is my models.py code.. from django.db import models from django.contrib.auth.models import User class Assignment(models.Model): title = models.CharField(max_length=400) teacher = models.ForeignKey(User ,on_delete=models.CASCADE) slug = models.SlugField() def __str__(self): return self.title class GradedAssingnment(models.Model): student = models.ForeignKey(User,on_delete=models.CASCADE) assignment = models.ForeignKey(Assignment,on_delete=models.SET_NULL, blank=True , null=True) grade = models.FloatField() def __str__(self): return self.student.username class Choice(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Question(models.Model): question = models.CharField(max_length=1000) choice = models.ManyToManyField(Choice,related_name="hoice") answer = models.ForeignKey(Choice, on_delete=models.CASCADE , related_name='answer') assignment = models.ForeignKey(Assignment,on_delete=models.CASCADE ,related_name='questions') order = models.SmallIntegerField() def __str__(self): return self.question -
Django rest framework empty field in partial update not updated
When I try to do a partial update with patch or a update with put. The object first looks like this: { "name":"Amsterdam 1", "location":"Amsterdam", "client":"b9c7d1c9-4b1b-4f0d-af30-2d8ffb97647e" } Then I remove the client on the object and thus send this back: { "name":"Amsterdam 1", "location":"Amsterdam" } But this does not remove the client from the object. The model looks like this: class FixedLocation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=155) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True) location = models.CharField(max_length=263) And this is how my serializer looks class FixedLocationSerializer(serializers.ModelSerializer): class Meta: model = models.FixedLocation fields = ["id", "name", "location", "client"] I expect when I don't send client back that it gets removed from the object. Does anybody know how I can achieve this? I also tried playing with null and blank on the foreign key. -
How can i link AI with django for movie recommendation system
i want to implement AI in my django .I am making movie recommendation system and i hav done simple recommendation system in jupyter notebook. So how can i link recommendation part and django? -
The view ProductCreateView didn't return an HttpResponse object. It returned None instead
How to redirect to another page from def form_valid(self): inside a generic FormView. I know I should do something like Super(className, self).form_valid(form): but this will never redirect to a dynamic link, but will only go to the success URL Here is my code : class ProductCreateView(FormView): form_class = ProductCreateForm template_name = 'back_office/product_create_form.html' success_url = reverse_lazy('product_recipe_wrapper') def form_valid(self, form): category = Category.objects.get(id=self.kwargs['pk']) name = form.cleaned_data['name'] image = form.cleaned_data['image'] big_size = form.cleaned_data['big_size'] mid_size = form.cleaned_data['mid_size'] small_size = form.cleaned_data['small_size'] new_product = Product.objects.create(category=category, name=name, image=image) big_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=1), sell_price=big_size) mid_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=2), sell_price=mid_size) small_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=3), sell_price=small_size) if small_size_object.sell_price != 0: return reverse_lazy('product_small_recipe', args=[small_size_object.id]) def get_context_data(self, *args, **kwargs): context = super(ProductCreateView, self).get_context_data() context['category'] = Category.objects.get(id=self.kwargs['pk']) return context -
Why can't i access to all the info in my partyinstancemodel?
my admin model [my listview ][2] obtained result my model Expected Result [my template file ][4] -
Materialize CSS select dropdown arrow displaced
Below is a screen shot of the materialize css as seen from: https://materializecss.com/select.html But for some reason, I get the little arrow of the drop down under the list rather than on the side. I am using Django 3. How do I fix this? And the following is the HTML of the rendered page: <html><head> <meta name="viewport" content="width = device-width, initial-scale = 1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"> </script> <script> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('select'); var instances = M.FormSelect.init(elems); }); </script> </head> <body class="vsc-initialized"> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo right">SIW</a> <ul id="nav-mobile" class="left hide-on-med-and-down"> <li><a href="/">Home</a></li> <li><a href="/Contact">Contact</a></li> </ul> </div> </nav> <div class="section"> <div class="row"> <form class="col s12"> <div class="input-field col s4"> <div class="select-wrapper"><input class="select-dropdown dropdown-trigger" type="text" readonly="true" data-target="select-options-07dbac11-476d-4358-8e69-a8d561e0df80"><ul id="select-options-07dbac11-476d-4358-8e69-a8d561e0df80" class="dropdown-content select-dropdown" tabindex="0" style=""><li class="disabled selected" id="select-options-07dbac11-476d-4358-8e69-a8d561e0df800" tabindex="0"><span>Choose your option</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df801" tabindex="0"><span>Option 1</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df802" tabindex="0"><span>Option 2</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df803" tabindex="0"><span>Option 3</span></li></ul><svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg><select tabindex="-1"> <option value="" disabled="" selected="">Choose your option</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select></div> <label>Materialize Select</label> </div> </form> </div> </div> <!--JavaScript at end of body for optimized loading--> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <div class="hiddendiv common"></div></body></html> -
Django form not saving multiple images into database
I am currently learning django. My django form is only saving a single image into the database even after selecting multiple images. any help will be highly appreciated. Here is my code; models.py class Post(models.Model): post = models.TextField(max_length=500, null=False, blank=False) image = models.ImageField(blank=True) 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 @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 class CreatePostForm(forms.ModelForm): image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Post fields = [ 'post', 'image'] views def home(request): context = {} form = CreatePostForm(request.POST or None, request.FILES or None) images = request.FILES.getlist('images') if form.is_valid(): for img in images: Post.objects.create(image=img) obj = form.save(commit=False) obj.author = user obj.save() form = CreatePostForm() context['post_form'] = form return render(request, 'posts/home.html', context) -
Not successfully added my profile model fields data to database django
My models.py file from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() from django import forms from django.contrib.auth.models import User from .models import Profile My forms.py file class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'password') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('bio', 'location', 'birth_date') My views.py file def signup(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): username = user_form.cleaned_data['username'] email = user_form.cleaned_data['email'] password = user_form.cleaned_data['password'] bio = profile_form.cleaned_data['bio'] location = profile_form.cleaned_data['location'] user = User.objects.create_user(username,email,password) user.save() usr = User.objects.get(id=id) profile = Profile(user=usr, bio=bio, location=location) profile.save() messages.success(request, _('Your profile was successfully updated!')) return redirect('login') else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'profile.html', { 'user_form': user_form, 'profile_form': profile_form }) Not successfully added my profile model fields data to database but added id.Please help Not successfully added my profile model fields data to database but added id.Please help Not successfully added my profile model fields data … -
Custom Django manager filter
I'm using a custom manager for getting correct queryset class ReportManager(models.Manager): def get_queryset(self): queryset = None for subclass in BaseReport.__subclasses__(): try: reports = ( subclass.objects.select_related('aircraft', 'flight') .only('id', 'aircraft', 'flight', subclass.TRIGGER_FIELD) .annotate( description=F(subclass.TRIGGER_FIELD), report_datetime=F(subclass.DATETIME_FIELD), ) ) if not queryset: queryset = reports else: queryset = queryset.union(reports) except AttributeError: pass return queryset So the problem is when I'm trying to use the .filter() method from this manager, it doesn't work. I've checked the SQL query, there is no WHERE or LIKE keywords for filtering. I guess it's all because I'm using .only() -
Django says Pillow is not installed even though it is
I keep getting the same error when I try to run manage.py runserver: Cannot use ImageField because Pillow is not installed. I have seen several threads made by people that have encountered the same problem but none of them have a straightforward fix to this issue. I have already installed Pillow (pip install Pillow and pip3 install Pillow). I have uninstalled it several times, and reinstalled it. But whenever I run my server it says that Pillow is not installed. I am on Windows 10. Any help would be appreciated. -
Django - Display specific JSON parts only
I have a file that has some JSON data .. I click a button and it renders on my HTML page ... However I only want to see specific pieces from the file Here is my view.py def read_file(request): f = open('output.txt', 'r') file_content = f.read() f.close() context = {'file_content': file_content} return render(request, "index.html", context) Here is my html <html> <head> <title> Test Test 123 </title> </head> <body> <form action="/open_file/" method="post"> <input type="submit" value="Get Details"> <br><br> {% csrf_token %} {{ file_content | linebreaks }} </form> </body> </html> In the textfile the JSON looks like this ====================Response==================== { "responseBody": { "errorId": 200, "errorMsg": "ok", "userDetails": { "fname": "Andy", "lname": "Test", "status": "YES", "email": "testuser@.com", "userName": "usernametest1212", "deviceDetails": { "type": "Mobile", "osVersion": "5.0.0", "nickname": "Test Telephone", "deviceModel": "Samsung" }, "devicesDetails": [ { "type": "Watch", "osVersion": "iOS 11", "email": null, "hasWatch": yes }, } What i would like to see is the following: ErrorMsg UserDetails - username and email deviceDetails - type and device model -
How to add a background imageas static image in django
please help me with this. I have an image slider. it shoud add like this bellow.. <div class="slider-item" style="background-image: url('img/hero_2.jpg');"> <div class="container"> <div class="row slider-text align-items-center justify-content-center"> <div class="col-md-8 text-center col-sm-12 element-animate"> <h1>Delecious Food</h1> <p class="mb-5">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi unde impedit, necessitatibus, soluta sit quam minima expedita atque corrupti reiciendis.</p> <p><a href="#" class="btn btn-white btn-outline-white">Get Started</a></p> </div> </div> </div> </div> Not working like these ways <div class="slider-item" style="background-image: url({%static'/img/hero_1.jpg'%});"> or <div class="slider-item" style="background-image: url{%static'/img/hero_1.jpg'%}"> I don't want to add like an img tag like this way " <img src="{% static '/img/hero_2.jpg' %}" />" I am using Django latest version with python 3.0 all are latest version Thank you -
Django Create table statement return error - Database Error ORA-00922: missing or invalid option
I am trying to create a table in my oracle database from django view using the input from the user. Upon collecting the inputs and converting it to a string. I am able to get the below as string.. CREATE TABLE Zen.TableSample (TableSample_id NUMBER GENERATED BY DEFAULT AS IDENTITY NOT NULL, EMPNAME VARCHAR2(100), PRIMARY KEY(TableSample_id) ) TABLESPACE "MYTABLESPACE"; I have it in a variable called "sqlstring" and then I am trying to create the table using the following code.. with connection.cursor() as cursor: cursor.execute(sqlstring) print("Query Executed") I am getting an error as "Database Error ORA-00922: missing or invalid option" Any advise on how to fix this.. Please advise. -
How do I access other model's instances using @property and Foreignkey in Django?
I have this simple example to illustrate what I would appreciate your help with. from django.db import models # Create your models here. class A (models.Model): job = models.TextField name = models.ForeignKey('B', models.DO_NOTHING) @property def nick(self): return self.name.surname class B (models.Model): surname = models.TextField() I would expect 'nick' to have the value of a given related surname when I will need to use it somewhere later on. Instead, the surname gives the following error: 'Unresolved attribute reference 'surname' for class 'ForeignKey'' How to achieve that when I somewhere use 'nick' it will return the surname? Thank you in advance! -
Django signals with ATIMIC_REQUESTS=True
Using Django (and DRF) If I'm set ATIMIC_REQUESTS=True on the Database config, would this apply for signals as well? I'm trying to understand if there is a chance our transaction is finished after response -
How to send data from localhost to server using Python requests?
I am trying to send data from localhost to an API in remote server using Python Requests & Django through an API: /api/send-data/ Path for /api/send-data/ in urls.py is path('send-data/',view_send_data.send_data,name='send_data') This is my view_send_data.py in my localhost: @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def send_data(): # defining the API-endpoint API_ENDPOINT = "http://68.183.89.234/api/screen/" # data to be sent to API data = {'data':1234} # sending post request and saving response as response object r = requests.post(url = API_ENDPOINT, data = data) print(r.json()) return Response({"success": True}, status=status.HTTP_200_OK) Path for api at http://68.183.89.234/api/screen/ in urls.py is path('screen/',views_fr.screen_display,name='screen') This is my views_fr.py in my remote server: @api_view(['POST']) def screen_display(request): if request.method == 'POST': return Response({"success": True, "response": request.data}, status=status.HTTP_200_OK) When I call "http://127.0.0.1:8000/api/send-data/" in my browser, I am getting 405 Method Not Allowed Is this the correct way to do it or am I missing something? Thank you. -
Can we create foreign key without models in Django?
I am using SQL Server database and Django. I have a Database named as Person Database and Other database as Student Database. In Person database I created models, but in Student database there are no models because the tables and data are already existing. So I am getting data of Student database using Pyodbc. Now I am creating a new model in Person database where I need to create a foreign key for student database. Can Anyone help me out how to do it. -
CASE types text and integer cannot be matched
I want the value of the respective field using CASE in Django. The Django query that I have written is as below: Ads.objects.filter(adslot__clients__id__in = clients) .annotate(hour = models.functions.ExtractHour('specific_time')) .annotate(mins = models.functions.ExtractMinute('specific_time')) .annotate(st = Concat('hour', Value(':'),'mins')) .annotate(ad_logic_value = Case(When(specific_time__isnull=False,then="st"),When(no_of_times_per_hr__isnull=False,then="no_of_times_per_hr"), When(after_n_songs__isnull=False,then="after_n_songs"),distinct = True,output_field=models.TextField())).values('ad_logic_value') Unfortunately, When I hit the API on Postman I get the error as below: ProgrammingError at /api/adinformation/ CASE types text and integer cannot be matched LINE 1: ... "core_ads"."no_of_times_per_hr" IS NOT NULL THEN "core_ads"... The Django Model is as followed: class Ads(models.Model): ad = models.ForeignKey('Song') no_of_times_per_hr = models.IntegerField(blank=True, null=True) after_n_songs = models.IntegerField(blank=True, null=True) specific_time = models.TimeField(blank=True, null=True) Can anyone suggest what could be done in order to make this query work? Note: I cannot have two separate fields for ad_logic_values.