Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serialization of GeoJson with Django Rest (Different features in one collection)
How is it possible to serialize/desirialize a GeoJson with Django (GeoDjango or django-rest-gis) with multiple different type of features ( Points, Polygons, Lines) I got different models for each of the geo types, which are connected to a model named Route: class Marker(Model): route = ForeignKey(Route, on_delete=CASCADE) popup_html = TextField() point = PointField() class Meta(Model.Meta): pass class Polygon(Model): route = ForeignKey(Route, on_delete=CASCADE) polygon = PolygonField() class Meta(Model.Meta): pass class Route(Model): name = CharField(max_length=255) class Meta(Model.Meta): pass And my Serializer looks like this class RouteMarkerSerializer(GeoFeatureModelSerializer): class Meta: model = Marker geo_field = "point" class RoutePolygonSerializer(GeoFeatureModelSerializer): class Meta: model = Polygon geo_field = "polygon" And i want to get a output for the viewset something like this: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 8.88393, 51.038918 ], [ 9.039142, 51.085495 ], [ 9.100952, 50.945624 ], [ 8.88393, 51.038918 ] ] ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ 9.066102, 51.024539 ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ 8.951007, 51.010103 ] } } ] } I dont get to figure it out, how to do this. If i'm serializing … -
Date sorting in Datatable in the format of mm/dd/yyyy
I used the Datatable plug-in in my Django project. My data is dynamic data from a working google sheet. The date format of the first column of my data is mm/dd/yyyy, which cannot be sorted properly by Datatable. I converted the date to other formats, but it still cannot be sorted properly by Datatable. I tried the following codes in my HTML file: <td data-sort='YYYYMMDD'>{{element.date}}</td> It can be sorted by the correct date sequence in this way. However, the sequence will be "fixed" and I cannot sort the date with a reverse sequence by clicking the "sorting" option -
Pass nested dictionary from views to template django
So, I'm new to Django and I'm trying to pass data from my view to a template. I've understood how to pass the classic dictionary but I now need to use a nested dictionary. For instance, I have a dictionary as below my_dictionary = {0: {'title': 'Beyond the Soul', 'id': '2Uy66My5oKcBEIW7DvVk3V'}, 1: {'title': 'The Groove Cartel Selection', 'id': '1pHtICGI68RmWEKnnP5wGr'}, 2: {'title': 'STMPD RCRDS TOP 50', 'id': '1OIzwJTbrOeZTHvUXf5yMg'}, 3: {'title': 'House Party by Axwell', 'id': '1tl4L77FJju5zp9bJC83u8'}} From my view I'm returning return render(request, 'show_playlist.html', my_dictionary ) but If I use {{ main_playlist[0] }} it gives Could not parse the remainder error Is there a way to access nested dictionary in templates? -
Django Forcing BigAutoField even though Default is set to AutoField
so I upgraded from django 3.1 to 3.2 and on two of my models when I make migrations it keeps forcing me to change the auto id to BigAutoField even though I have (and had) DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' in my settings file before I updated. operations = [ migrations.AlterField( model_name='device', name='id', field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ) What is strange is that it is only affecting a couple models, but the rest are fine and they all use AutoField as well. I am not against using BigAutoField but the migration fails because of foreignkey constraints. I have deleted the migrations in question and also scrubbed them from the applied migrations table in the database. How can I stop Django from forcing this migration? I am at a loss right now. -
django - React - Axios: Data not being saved in database
I am trying to create products through a react js component using axios post request. In django log i see an OPTION request geting a 200 status code, but data not being saved in the DB. when doing it through postman it is working fine, which makes me think the problem is in the axios request. Thanks in advanced. models.py class Product(models.Model): title = models.CharField(max_length=32) notes = models.TextField() picture = models.ImageField(upload_to='product_images', null=True, blank=True) amount = models.IntegerField(default=0) @receiver(post_save, sender='product.Transaction') def update_amount(sender, **kwargs): product = Product.objects.get(title=kwargs['instance'].product) if kwargs['instance'].transaction_type == 'IN': product.amount += kwargs['instance'].amount product.save() else: if product.amount - kwargs['instance'].amount > 0: product.amount = product.amount - kwargs['instance'].amount product.save() def __str__(self): return self.title views.py class ProductCreateView(generics.CreateAPIView): serializer_class = ProductSerilizer permission_classes = (permissions.IsAuthenticated,) queryset = Product.objects.all() serializers.py class ProductSerilizer(ModelSerializer): class Meta: model = Product fields = '__all__' settings.py ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product', 'rest_framework', 'corsheaders', 'rest_framework.authtoken' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DATETIME_FORMAT': '%d-%m-%Y', } CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_ALL_ORIGINS = True AddProducts.js import React, {useState} from 'react'; import axios from 'axios' import { useNavigate } from "react-router-dom"; function AddProduct() { const [medicineTitle, setMedicineTitle] = useState(''); … -
how to return status in Response in json using django
I am creating an app where I am calling an API but there are five conditions, but the issue is I dont want to return after each conditon rather I want 5 response varibles and return that variable afterward which ever ran, but i am getting error unhashable type: 'dict' res = Response() if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) return (res) but the issue when I add status along with each data inside the res, i am getting this above error, for now I am return five statements each with their own status, but this doesn't look, so is it possible to return status along with all those statements. -
Latency for complexe request (DJango SQL)
I'm running a ("complex") query in SQL. Results returned to me in 0.3193ms from a MariaDB CLI. I transpose the query to Django through raw SQL, I get a return in 765.38 ms. The "Project" table contains 6000 entries. Here is my query (I'm getting bad results using the ORM's query system): Projet.objects.raw("SELECT P.id_projet AS id_projet, P.code_projet AS code_projet, S.nom_commercial AS id_societe__nom_commercial, P.date_initial AS date_initial, E.label_entite AS id_entite__label_entite, TC.label_type_contract AS id_type_contract__label_type_contract FROM HOME_PROJET AS P, HOME_TYPE_CONTRACT AS TC, HOME_ENTITE AS E, HOME_SOCIETE AS S WHERE id_projet IN ( SELECT Z.PK FROM ( SELECT primary_key_id AS PK FROM HOME_OBJECTS_H_PERM WHERE id_user = 1 AND objects_type = 'Projet' AND (id_type_perm IN (2, 5)) UNION SELECT primary_key_id AS PK FROM HOME_OBJECTS_H_GROUPPERM WHERE (id_group IN (1, 2)) AND objects_type = 'Projet' AND (id_type_perm IN (2, 5)) ) AS Z ORDER BY Z.PK ) AND P.id_type_contract = TC.id_type_contract AND P.id_societe = S.id_societe AND P.id_entite = E.id_entite;") SQL aliases are configured to map to model fields. Which solution(s)? -
How to store and display datetime field of a Model according to the end user's location in django?
models.py class PostModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now_add=True) title = models.TextField(null=True) body = models.TextField(null=True) def __str__(self): return str(self.user) .html {% extends 'base.html' %} {% block content %} {% for post in posts %} {{post.date_time}} <br> {{post.title}} <br> {{post.body}} <br> {% for image in post.imagespostmodel_set.all %} <img src="{{image.images.url}}" alt="postimage" style="width: 300px;"> <br> {% endfor %} <hr> <hr> {% endfor %} {% endblock %} I have to specifically set the timezone in setting.py, but I want to display the time according the user location. -
Is this possible to add more required Fields in django rest framework (while log in)
At first i wanna say that my code is not important here. I wanna understand logick how this works. So when i try to Login with Django Rest Framework i need to pass 2 fields "Password and Username". Is this possible to add more required fields for example i need to pass email to log in. And How do i make it compare to data that i passed while registering user. (sorry for eanglish) I wanna make this: enter image description here Fields only required to log in: enter image description here Images Fixed -
Django Form - Conditional field display using JQuery
Disclaimers: I've been hitting many dead ends. After trying 10+ different questions and answers on Stack Overflow alone I've hit a wall. I am hoping I can accomplish this with a direct question. Please be gentle. I have spent days searching Stack Overflow and the Interwebs to try and get this working. There are MANY suggestions, and none of them have worked for me so far. I will confess I am not very knowledgeable with JS and this is likely why I'm stumbling hard over this requirement. If you have feedback on the quality of this question please comment with constructive criticism. Just telling me it's a poorly framed question won't help. However, sharing specific examples of what I could have done to frame the question in a more helpful manner would be great. Hopefully, you will be able to ascertain that I have gone to great efforts to post a substantive summary of the desired objective along with what I have tried. This implementation is using Django 4.0 and Bootstrap5 with CrispyForms. Objective: The user selecting a value in one field determines whether another field is shown or hidden. By default, the conditional field has a value of "No". … -
Reverse query in Django Many to Many
I have a problem in django reverse many to many. Basically, I think I am missing something that I couldn't understand properly yet. I have these models and views. models.py class TheorySyllabus(models.Model): name = models.CharField(max_length=100, null=True, blank=True) subject_duration = models.ManyToManyField( SubjectDuration, related_name='subject_durations') course_type = models.ForeignKey( CourseType, on_delete=models.DO_NOTHING, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'Theory Syllabus' class TheoryCourse(models.Model): name = models.CharField(max_length=100) student = models.ManyToManyField(Student, related_name='theory_courses') theory_syllabus = models.ForeignKey( TheorySyllabus, on_delete=models.DO_NOTHING, null=True, blank=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField() fiscal_code = models.CharField(max_length=50) phone = models.CharField(max_length=50) license = models.ForeignKey( License, on_delete=models.PROTECT, blank=True, null=True) picture = models.ImageField( blank=True, null=True, default='default.png') id_card = models.ForeignKey( IDCard, on_delete=models.PROTECT, blank=True, null=True) address = models.CharField(max_length=100) cap = models.CharField(max_length=10) city = models.CharField(max_length=100) province = models.CharField(max_length=100) country = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.user.first_name + ' ' + self.user.last_name views.py class CourseListView(ListView): model = TheoryCourse queryset = TheoryCourse.objects.filter( is_active=True).order_by('-created_at') template_name = 'theory/course_list.html' context_object_name = 'theory_courses' paginate_by = 10 template <div class="card-body table-responsive p-0"> <table class="table table-hover text-nowrap table-bordered"> <thead> <tr> <th>Course … -
Why I can't fetch the json response of django using javascript fetch API?
I am new to JavaScript. I'm working on a project in which I'm using Django in the backend. My Django views function will produce a JSON response which my javascript fetch will get it. Here is my Django views function that produces a JSON response. My motive is to make a like button that will update the like button's appearance and the number of likes by clicking on that button without reloading the whole page. This is the last requirement of my project. I am trying for a long time, a couple of days. def likepost(request,posts_id): posts = NewPost.objects.get(id = posts_id) is_like = False for like in posts.likepost.all(): if like == request.user and request.method == "POST": is_like = True break if not is_like: posts.likepost.add(request.user) else: posts.likepost.remove(request.user) posts.save() # serialize_obj = serializers.serialize("json",posts_id) return JsonResponse({ "is_like" : is_like, "num_like" : posts.likepost.count() },safe=False) My javascript will make an API of the JSON data generated the above views function using fetch. Here is my javascript full code. document.addEventListener("DOMContentLoaded",function(e){ // const colon = document.createElement('div'); // colon.setAttribute('id','colon') e.preventDefault() // const likebtn = document.createElement('button'); // likebtn.setAttribute('class','likebtn btn btn-primary'); // likebtn.setAttribute('class','likebtn'); // document.querySelector('.card-footer').appendChild(likebtn); // document.querySelector('.likebtn').innerHTML = "Like"; document.querySelector(`#likebtn${posts_id}`).onsubmit = like_function(); // document.querySelector('.likepost').addEventListener('click', ()=> like_function('likepost')); }) // let is_like … -
How to solve this friend-request system error in my django project?
So in my django project i have this friend request system, it works for the most part (i think), i can send friend requests and then those respective users actually recieve the friend request, but when i try to accept that friend request it shows this error:error these is my views.py( the views i use in the friend request system have friends or something in their name, everything else is for other staff) from django.shortcuts import render from django.contrib.auth.decorators import login_required from .forms import UserRegistration, UserEditForm,PostForm from django.views import generic from .models import Post,Friend_Request from django.contrib.auth.models import User # Create your views here. def friends(request): users = User.objects.all() return render(request, 'authapp/friendrequest.html', {'allusers':users}) def friends_accept(request): all_friend_requests = Friend_Request.objects.all() current_user = request.user to_user = User.objects.get(id = current_user.id) all_friend_requests = Friend_Request.objects.filter(to_user = to_user) return render(request, 'authapp/friends_request.html', {'all_friend_requests':all_friend_requests}) def download(request): context = { "welcome": "Welcome to your dashboard" } return render(request, 'authapp/download.html', context=context) def index(request): queryset = Post.objects.all() context= {'post': queryset} return render(request, "authapp/post.html", context) def blogs(request): posts = Post.objects.all() posts = Post.objects.filter().order_by('-created_on') return render(request, "authapp/post.html", {'posts':posts}) class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'authapp/post.html' class PostDetail(generic.DetailView): model = Post template_name = 'authapp/post_detail.html' @login_required def send_friends_request(request,userID): from_user = request.user to_user = User.objects.get(id = userID) … -
Django Update Instance with Email from 2 Related Objects
I have these models: class Contact(models.Model): email = models.EmailField(max_length=200, blank=False, null=False) class Account(models.Model): #account owner contact = models.OneToOneField(Contact, on_delete=models.CASCADE) class IndividualProfile(models.Model): account = models.OneToOneField(Account, blank=False, null=False, default='', on_delete=models.CASCADE) and I want to import an IndividualProfile, through django-import-export. In the sheet I'm importing, I have an email field that I will use to see if the Contact exists. Here is the logic I currently have been working on: class IndividualProfileResource(resources.ModelResource): class Meta: model = IndividualProfile clean_model_instances = True def before_import_row(self, row, row_number=None, **kwargs): self.temp_email = row["email"] def after_import_instance(self, instance, new, row_number=None, **kwargs): """ Create any missing Contact entries prior to importing rows. Create any missing Account entries prior to importing rows. """ if self.temp_email: # create contact first contact, created = Contact.objects.seal().get_or_create(email=self.temp_email) # # check if account exists account, created = Account.objects.seal().get_or_create(contact=contact) # # check if profile exists instance.account = account but doing this marks an error in the preview when I try to upload with an existing email. I was expecting it to update the existing IndividualProfile instance, but it did not. How may I fix this? Any help is appreciated. -
Adding list data in a JavaScript line chart - Django project
I created a list and defined it in my views.py: mydata = [{'date': '2020-01-02T00:00:00Z', 'value': 13}, {'date': '2020-01-03T00:00:00Z', 'value': 2}, {'date': '2020-01-06T00:00:00Z', 'value': 5}] I want to add my own data in a template js chart in my HTML file: <script> var chart = am4core.create("chartdiv", am4charts.XYChart); chart.paddingRight = 20; var data = []; var visits = 10; for (var i = 1; i < 50000; i++) { visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10); data.push({ date: new Date(2018, 0, i), value: visits }); } chart.data = data; var dateAxis = chart.xAxes.push(new am4charts.DateAxis()); dateAxis.renderer.grid.template.location = 0; dateAxis.minZoomCount = 5; dateAxis.groupData = true; dateAxis.groupCount = 500; var valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); var series = chart.series.push(new am4charts.LineSeries()); series.dataFields.dateX = "date"; series.dataFields.valueY = "value"; series.tooltipText = "{valueY}"; series.tooltip.pointerOrientation = "vertical"; series.tooltip.background.fillOpacity = 0.5; chart.cursor = new am4charts.XYCursor(); chart.cursor.xAxis = dateAxis; var scrollbarX = new am4core.Scrollbar(); scrollbarX.marginBottom = 20; chart.scrollbarX = scrollbarX; var selector = new am4plugins_rangeSelector.DateAxisRangeSelector(); selector.container = document.getElementById("selectordiv"); selector.axis = dateAxis; </script> I know I should change the chart.data = data, but when I replaced it with chart.data = {{mydata}}, the chart didn't displat anything. I tried chart.data = [{'date': '2020-01-02T00:00:00Z', 'value': 13}, {'date': '2020-01-03T00:00:00Z', 'value': 2}, … -
Building a levels with tasks app in django
I am new to django and I am building a simple app that has some levels with tasks which a user have to complete. It has 7 levels, a user have to complete a specific level (which has a task) to unlock the next level. Unless he completes the previous task he can't access the next level or the webpage or url. So there is a Groups thing in django. Shall I use that to achieve the functionality or is there any other stuff I shall do/use? Thank you. -
get_absolute_url() is not working in django
I have get_absolute_url in model, but when i call in HTML i have some problem. i have searched in google many times, but i haven't idea what happened. Could not parse the remainder: ' 'object.get_absolute_url' pk=object.id' from 'url 'object.get_absolute_url' pk=object.id' it's my code --> views.py class ProfileHome(ListView): template_name = "profile/home.html" model = Question context_object_name = "question" models.py class Question(models.Model): title = models.CharField(max_length=100, verbose_name=_("სათაური")) text = models.TextField(verbose_name=_('კითხვა')) category = models.ManyToManyField(Category, related_name="categories",verbose_name=_("კატეგორია")) user = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name=_("მომხმარებელი")) def get_absolute_url(self): return reverse("Profile:question-detail", kwargs={'pk': self.pk}) def __str__(self): return self.title html {% extends "base.html" %} {% block content %} {% include "./navbar.html" %} <div class="relative pl-96 ml-12 mt-12"> {% for object in question %} <a href="{{ url 'object.get_absolute_url' pk=object.id }}"> <div class="p-6 mb-12 w-7/12 bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700"> <div class="mb-2 flex "> {% for a in object.category.all %} <p class="mr-2 text-sm text-blue-500">#{{ a.name }}</p> {% endfor %} </div> <a href="#"> <h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">{{ object.title }}</h5> </a> <p class="mb-4 font-normal text-gray-700 dark:text-gray-400">{{ object.text }}</p> <a href="#" class="inline-flex items-center py-2 px-3 text-sm font-medium text-center text-white bg-blue-700 rounded-lg hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"> წაიკითხე მეტი <svg class="ml-2 -mr-1 w-4 h-4" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10.293 3.293a1 1 0 011.414 … -
How to use Celery to upload files in Django
I was wondering how I can use Celery workers to handle file uploads. So I tried implementing it on a simple class. I overrided the create class in my ModelViewSet. But apparently Django's default json encoder does not serialize ImageFields (Lame). I'll really appreciate it if you guys could tell me how I can fix this. Here is what I came up with: serializers.py: class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ['id', 'image'] tasks.py: from time import sleep from celery import shared_task from .models import ProductImage @shared_task: def upload_image(product_id, image): print('Uploading image...') sleep(10) product = ProductImage(product_id=product_id, image=image) product.save() views.py: class ProductImageViewSet(ModelViewSet): serializer_class = ProductImageSerializer def get_queryset(self): return ProductImage.objects.filter(product_id=self.kwargs['product_pk']) def create(self, request, *args, **kwargs): product_id = self.kwargs['product_pk'] image = self.request.FILES['image'] image.open() image_data = Image.open(image) upload_image.delay(product_id, image_data) return Response('Thanks') and here's the my model containing my ImageField: class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to='store/images', validators=[validate_image_size]) -
Django - Two choicefield selector insted of one when use select2
I want to make a choicefield form that is searchable When I use select2, two choicefields selector are created this screen shot show my problem this is my form: class ClientSelectForm(forms.ModelForm): def __init__(self,*args,**kwargs): self.initial_client = kwargs.pop('initial_client') self.CLIENT_LIST = Client.objects.all() self.CLIENT_CHOICES = [('-----', '--انتخاب مشتری--')] for client in self.CLIENT_LIST: d_t = (client.uniqueId, client.clientName) self.CLIENT_CHOICES.append(d_t) super(ClientSelectForm,self).__init__(*args,**kwargs) self.fields['client'] = forms.ChoiceField( label='انتخاب مشتری مربوطه', choices = self.CLIENT_CHOICES, widget=forms.Select(attrs={'class': 'form-control mb-3'}), ) class Meta: model = Invoice fields = ['client'] and this my template <form class="" action="#" method="post"> {% csrf_token %} {{client_form}}" <button type="submit" class="btn btn-primary">افزودن مشتری</button> </form> -
How to make model field that can has several values in django
I want to make a blog in Django. The blog has Article, Author ... models. each article has many resources. it looks like this on the article page: Resources: Medium, Hashnode, Dev community, ... I want that while adding an article, the admin can dynamically these article resources. for the author, I want to add social links. every author's social media are different. one may have Facebook, LinkedIn ... and the other may have Instagram, Twitter, ... I want the admin (or author) can add any social media for the authors. -
Django ORM - getting sum of annotated column after GROUP BY clause
Here I have my QuerySet: queryset = queryset.annotate( calc_date=Func( models.Value(date_start), models.Value(date_end), models.Value(interval), function='generate_series', output_field=models.DateField() ), complete_day=service.complete_day, fact_performance=service.fact_performance, plan_performance=service.plan_performance, ).values('calc_date').annotate( total_fact=Sum('fact_performance'), total_plan=Sum('plan_performance'), ) At first I'm generating series of dates for every object in query and annotating calculation expressions based on each specific date, which is fact_performance and plan_performance. After that I'm using .values('calc_date') to trigger GROUP BY clause and calculate sum of performance values within each generated date, but unexpectedly, I got this error: django.core.exceptions.FieldError: Cannot compute Sum('fact_performance'): 'fact_performance' is an aggregate Is there some workaround to this problem? -
Placeholder Image not Loading Correctly Using Django
I'm working on a project which displays several listings created by users. If the user who created the listing uploaded an image, it shows the image uploaded by the user, otherwise it shows a placeholder image indicating there is no image available. This is shown both on the index page which lists the available listings and in the listing itself if the user goes there. When this is done in the index page it works without problems, however, on the listing page, despite being literally the same code, it doesn't work with the placeholder image (if the creator of the listing uploaded an image it shows without problems). The urls in settings.py are: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And in urls.py: urlpatterns = [ path("", views.index, name="index"), ... path("listing/<int:listing_id>", views.listing, name="listing"), ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In both cases (from the index page and the listing page) if I inspect the element i'm shown: <img src="media/images/No-Image-Placeholder.png"> However, if I right click the image and choose to open it in a new window, from the index (where it works well) the address will be "http://127.0.0.1:8000/media/images/No-Image-Placeholder.png", meanwhile, from the listing (where it doesn't work) it'll be "http://127.0.0.1:8000/listing/media/images/No-Image-Placeholder.png". … -
django-cms - the pages are visible only to the administrator
The pages are visible only to the administrator. After creating the page, I can only see it if I have administrator rights. If I go to 127.0.0.1:8000 from another browser, I will only see the menu. I installed django-cms using djangocms-installer: $ python3 -m venv env $ source env/bin/activate (env) $ pip install djangocms-installer (env) $ mkdir myproject && cd myproject (env) $ djangocms -f -p . my_demo (env) $ python manage.py runserver What am I doing wrong? -
Can I use a reverse relationship in a django-autocomplete-light search filter?
The field I need to search in belongs to a reverse 'diariaviagem' to 'viagem' relationship class DiariaViagem(models.Model): viagem = models.ForeignKey(Viagem, on_delete=models.CASCADE) fonte_pagamento = models.ForeignKey(FontePagamento, null=True, blank=True, on_delete=models.CASCADE) class ViagemAdmin(admin.ModelAdmin): list_filter = (FonteFilter,) filter class FontePagamentoViagemChangeListAutocomplete(autocomplete.Select2QuerySetView): model = FontePagamento def get_queryset(self): qs = self.model.objects.all() if self.q: qs = qs.filter(Q(diariaviagem__fonte_pagamento__codigo__icontains=self.q) | Q( diariaviagem__fonte_pagamento__descricao__icontains=self.q)) return qs class FonteFilter(FilterSelect2): title = 'Fonte de pagamento' # filter's title field_name = 'diariaviagem_set__fonte_pagamento' # field name - ForeignKey to Country model autocomplete_url = 'fonte_pagamento_viagem_change_list_autocomplete' # url name of Country autocomplete view is_placeholder_title = False widget_attrs = {'data-placeholder': 'Selecione'} The code displays the following error: type object 'Viagem' has no attribute 'diariaviagem_set__fonte_pagamento' If I just pass 'diariaviagem_set' or a property it returns: 'ReverseManyToOneDescriptor' object has no attribute 'get_queryset' Can I do something like this? -
Django postgres unique constraint name generation
When adding a new unique constraint on a django model, this will automatically create a name for this constraint in postgres. Does Postgres generate this name or is it Django? Is it deterministic? for example I use this model class MyModel(Model): field1 = TextField() field2 = IntegerField() class Meta: unique_together = ("field1", "field2") I got the name of the constraint with select constraint_name from information_schema.constraint_column_usage where table_name = 'myapp_mytable' I get a name like field1_field2_d04755de_uniq