Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find which site ids I have in Django Admin panel sites
I have deleted my previous site xxx.xxx.com and added a new site xx1.xxx.com. So then in the settings.py I have configured the site id to 2 and, yet it's not giving me the django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. error. How can I check the exact site ids I have right now with the shell. Because my admin panel is not loading too. I am pretty new to django. So apologies if this is a very basic one to ask. I tried to change the site id from 1 to 2 -
Django: Problems with Fileresponse in production
Django: Fileresponse works fine in local but it doesnt in deployment In local i did this @login_required @permission_required('plataforma.ADMIN', raise_exception=True) def admin_descargar_planilla(request,plantilla_id): try: plantilla = Plantilla.objects.get(pk=plantilla_id) except: return render(request, "plataforma/error.html",{"tipo_error":"No se puede realizar esta accion ya que la plantilla ya no existe"}) buffer = util.crear_pdf(plantilla) return FileResponse(buffer, content_type='application/pdf', filename=(plantilla.eett.username+" ("+str(plantilla.fecha)+")")) The function crear_pdf returns an io.BytesIO(). When I try to use this views in production I recieve an Internal Server error (500) from the server instead of an django error. In the deployment I'm using openlitespeed. Also I try using an existing pdf instead of a buffer but its worst because i receive error 404 saying the url doesnt exist when it exist (this also works fine in local) -
Hwo to save multiple vlaues, which are reteived from frontend, in database in django Many to Many relationship?
While adding a book, I have to get data from frontend. I created a AddBookForm form. Book and Author have Many-to-Many relationship. From the frontend Form I get the names of the authors for the corresponding book as a list(from dynamic input field). Now the data is saved but is stored incorrectly. I know this is not the optimized way to save many to many relationship data. Please help me do this in an optimized way. models.py: class Book(models.Model): name = models.CharField(max_length=200, null=False, blank=False) description = models.TextField(null=True, blank=True) no_of_copies = models.IntegerField(default=1, null=True, blank=True) status = models.CharField(max_length=15, choices=[('Out of Stock', 'Out of Stock'), ('Available', 'Available')], default='Available') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100, null=True, blank=True) books = models.ManyToManyField(Book) def __str__(self): return self.name class Genre(models.Model): name = models.CharField(max_length=50, null=True, blank=True) books = models.ManyToManyField(Book) def __str__(self): return self.name forms.py class AddBookForm(forms.ModelForm): authors = forms.CharField(max_length=255, required=False) genres = forms.CharField(max_length=255, required=False) class Meta: model = Book fields = '__all__' views.py def add_book(request): if request.method == 'POST': form = AddBookForm(request.POST) if form.is_valid(): book = form.save(commit=False) authors = request.POST.getlist('authors') book.save() for name in authors: author, created = Author.objects.get_or_create(name=name) author.books.add(book) return redirect("/") else: form = AddBookForm() context = {'form': form} … -
django-STATICFILES _DIRS not collecting
In my django project settings, I defined my static files like so: STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR + '/static' STATICFILES_DIRS = [ BASE_DIR +'/folder1', BASE_DIR + '/folder2', ] But collectstatic doesn't collect what is defined in "STATICFILES_DIRS". Even though it works locally, on the server it doesn't work. What am I doing wrong? -
How to add input from textarea tag in Django
I have been trying to fetch input from textarea tag in Django but its not working. this my form <form method="POST" action="/" > {% csrf_token %} <textarea class="form-control" id="comment" name="comment" rows="4"></textarea> <button type="submit" class="btn btn-primary btn-sm">Post comment</button> </form> this is my view ` if request.method=='POST': username = request.user comment = request.POST.get('comment') new_comment = Pcomments(username=username,comment=comment,date = datetime.date.today()) new_comment.save() ` -
Deserializing a nested object using Django Rest Framework ModelSerializer
I have this JavaScript code in the client sending a vacation object to the server: const vacation = { employee: currentEmployee, startDate: form.querySelector('#start-date').value, endDate: form.querySelector('#end-date').value, vacationReason: form.querySelector('#reason').value, status: 'P', }; const newData = new FormData(); newData.append('csrfmiddlewaretoken', getCSRFToken()); newData.append('vacation', JSON.stringify(vacation)); const postReq = new XMLHttpRequest(); postReq.open( 'POST', '/vacations/vacation-list' ) postReq.onreadystatechange = () => { if (postReq.readyState === XMLHttpRequest.DONE) { if (postReq.status === 201) window.location.replace('/vacations'); else prompt('BAD REQUEST.'); } } postReq.send(newData); The problem is that when I try to use VacationSerializer in the vacation_list view, serializer = VacationSerializer(data=json.loads(request.POST.get('vacation')) if serializer.is_valid(): serializer.save() I get serializer.errors: an 'employee' object already exists with this id. And it's essentially meant to be a vacation for an existing employee! I could not find a way to deserialize using ModelSerializer with an existing object as part of the referencing object. These are my ModelSerializers: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id', 'name', 'name', 'email', 'phoneNumber', 'address', 'gender', 'maritalStatus', 'availableVacationDays', 'approvedVacationDays', 'salary', 'birthDay'] class VacationSerializer(serializers.ModelSerializer): employee = EmployeeSerializer() class Meta: model = Vacation fields = ['id', 'employee', 'startDate', 'endDate', 'vacationReason', 'status'] def create(self, validated_data): employee_data = validated_data.pop('employee') vacation = Vacation.objects.create(**validated_data) vacation.employee = Employee.objects.get(id=employee_data['id']) return vacation I tried the above overriding of the create method, but it … -
trying to use djongo engine to connect to documentdb database using ssh tunnel
pymongo.errors.OperationFailure: namespace name generated from index name is too long, full error: {'ok': 0.0, 'code': 67, 'errmsg': 'namespace name generated from index name is too long', 'operationTime': Timestamp(1684956028, 1)} i'm trying to use djongo engine to connect to documentdb database using ssh tunnel -
Stuck with user profile, where users can submit there products. Can someone please help me?
I'm new to Django and working on a Django classified ads project. I've created models and templates already but now stuck with the user profile section. Where users can update there profile and submit there products, which they want to sell. I've already created super user, but really confused and don't know where to start for multiusers profile section so they users can post their products. -
Replace form.as_p with custom template
need help to use html templates instead of using the deafult django form.as_p enter image description hereenter image description hereenter image description here it tried adding labels with id and i was exxpecting them to match -
Sort objects by hit_count.hits
Using django-hitcount to count views with no issues. Now, how do I sort a QS by hits? For example, have a bunch of different animals: class Dog(models.Models): name = models.CharField(max_length=40) age = models.IntField() class DogDetailView(HitCountDetailView): model = Dog count_hit = True Viewing individual animals works fine and view counts go up. Now on a main page, I need to list each animal type by most viewed. I can get the list of dogs, but how do I sort it by hit_count? class AllAnimalsView(TemplateView): ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["dogs"] = Dogs.objects.all().order_by("-hit_count.hits") .... return context This gives: django.db.utils.OperationalError: (1054, "Unknown column 'hit_count.hits' in 'order clause'") -
NoReverseMatch Error during template rendering
I have this url that causes the error <a href="{% url 'page-two' item_1 item_2 %}"> The url should be rendered as /pages/36/some-story urls.py urlpatterns = [ path('pages/<slug:slug>', views.PageOneView.as_view(), name='page-one'), path('pages/<slug:slug_1>/slug:slug_2>', views.PageTwoView.as_view(), name='page-two'), ] views.py class PageOneView(View): def get(self, request, slug): run = Pages.objects.get(id=slug) item_1 = 36 item_2 = 'some-story' context = { 'item_1': item_1, 'item_2': item_2, } return render(request, "pages/page_1.html", context) class PageTwoView(View): def get(self, request, slug_1, slug_2) context = {} return render(request, "pages/page_2.html", context) The trackback says: Reverse for 'page-two' with arguments '('36', 'some-story')' not found. It seems like the url get's rendered correctly because I see the values I expected. But I still can't figure out where this error is coming from. What have I done wrong? -
Optimizing Django queries - reducing database requests & proper queryset access
My Views def home(request): q = '' if request.GET.get('q'): q = request.GET.get('q') rooms = Room.objects.select_related('host', 'topic').prefetch_related('participants').filter( Q(topic__name__icontains=q) | Q(name__icontains=q) | Q(description__icontains=q) ) topics = Topic.objects.select_related('user') profile = Profile.objects.filter(user=request.user) r_messages = Message.objects.select_related('user', 'room').filter(Q(room__topic__name__icontains=q)) return render(request, 'base/home-page.html', context={ 'rooms': rooms, 'topics': topics, 'profile': profile, 'r_messages': r_messages, }) My Models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.FileField(default='default.jpg', upload_to='profile_image', null=True) name = models.CharField(max_length=100, null=True, blank=True) bio = models.TextField(max_length=5000, null=True, blank=True) email = models.EmailField() username = models.CharField(max_length=100) def __str__(self): return f'{self.user}' def get_absolute_url(self): return reverse('user-profile', args=[str(self.user)]) class Topic(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return f'{self.name}' class Room(models.Model): host = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(Profile, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) # Save every time when we update created = models.DateTimeField(auto_now_add=True) # Only save when room was created class Meta: ordering = ['-updated', '-created'] def __str__(self): return f'{self.name}' class Message(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.body[:50]}' class Meta: ordering = ['-updated', '-created'] My Template {% for room in rooms %} <li> {{ room.topic.host }} <a href="{% url 'home' %}?q={{ room.topic.name}}">{{ room.topic.name}}<span>{{ room.topic.room_set.all.count}}</span></a> </li> … -
Published Google Play Store App not doing authentication but debug apk passes authentication
Assistance Am doing an app in ionic framework with JWT authentication coming from Django rest framework and encountering a very wierd problem, before I upload my app to Google play console it is able to login successfully but when I download the Open Test Version of Google play store am unable to login After some hours of research am thinking the problem is related to app signing and something to deal with API integrity What i have tried to do is upload my keystore file that i geneated using keytool to Google Play Console's App Signing Tab under App Integrity then also associated my app with the Digital Asset Links JSON but still encounter the same issue Anyone to help? What i have tried to do is upload my keystore file that i geneated using keytool to Google Play Console's App Signing Tab under App Integrity then also associated my app with the Digital Asset Links JSON but still encounter the same issue -
I'm using a standard Django login but I'm getting this error: Error exiting in Django 4.2.1
enter image description heremessage error when clicking link to logout message error when clicking link to logout urlpatterns content django.contrib.auth.urls in urls.py urlpatterns content django.contrib.auth.urls in urls.py Variable LOGOUT_REDIRECT_URL in settins.py Variable LOGOUT_REDIRECT_URL in settins.py file html index content button html logoutenter image description here I am creating logout, login works less logout -
How can I display all active sessions of logged in users using django-user-sessions?
Please I need someone to help me out on the django-user-sessions, I have tried the documentation but it is not showing me the full active sessions of the login user. Please I need help can someone show me the example views and template on how it should be. Thank you I have tried the django-user-sessions documentation, I have installed django-user-sessions and put user-sessions in my installed apps. -
How to create a web django system with a dynamic apps?
I need o create a django system with a dynamic apps. In another words: when the client buy the system, we will to enable whats apps they will use according to the contracted package and it needs to be intuitive because the sells time need to enable the apps without needing the dev. Can you guys already make something like this ?? I have no idea how start. -
How can I fix the '_TypeError' when adding a model to another model in Flutter with Django Rest API?
I'm really confused on how do I add director model to my show model. I'm writing Android application in Flutter, that uses local Django Rest API. This is Director Model in Django class Director(models.Model): name = models.CharField(max_length=20) surname = models.CharField(max_length=20) country = models.CharField(max_length=20) image = models.ImageField(null=True, blank=True, upload_to="images/") This is Shows Model in Django class Show(models.Model): name = models.CharField(max_length=50) annotation = models.TextField(max_length=1000) language = models.CharField(max_length=20, null=True) image = models.ImageField(null=True, blank=True, upload_to="images/") director = models.ForeignKey(Director, on_delete=models.CASCADE, null=True) This is Director Model in Flutter import 'package:flutter/widgets.dart'; class DirectorModel with ChangeNotifier { final int id; final String name; final String surname; final String image; DirectorModel({required this.id, required this.name, required this.surname, required this.image}); factory DirectorModel.fromJson(dynamic json) { return DirectorModel( id: json['id'], name: json['name'] as String, surname: json['surname'] as String, image: json['image'] as String, ); } static List<DirectorModel> directorFromSnapshot(List snapshot) { return snapshot.map((data) { return DirectorModel.fromJson(data); }).toList(); } } This is Shows model in Flutter import 'package:flutter/widgets.dart'; import 'package:kulises_app/models/directors.dart'; class ShowsModel with ChangeNotifier { int id; String name; String annotation; String language; DirectorModel director; String image; ShowsModel( {required this.id, required this.name, required this.annotation, required this.language, required this.director, required this.image}); factory ShowsModel.fromJson(dynamic json) { return ShowsModel( id: json['id'], director: DirectorModel.fromJson(json['director']), name: json['name'] as String, annotation: json['annotation'] … -
Python Django - process long running views in the background
What is the best approach to send a long running process to the background in Python when working within the Django framework. Summary: I'm using a Django web app alongside chatGPT to create a certain resource for my users. The problem is waiting on the response from openAI makes for a terrible user experience. For this reason I would like to offload this work. Ideally, I would like to send another http request to my server with the needed payload and run it in the background, then alert users when it's completed. Here's the synchronous code @login_required def createx(request): if request.method == "GET": return render(request, 'x/x_create.html', {}) else: request_body = json.loads(request.body) #get user profile my_user = request.user #make sure the user is premium if not my_user.is_premium_user(): #redirect to home page #set error message messages.error(request, 'You must be a premium user to create a x') return redirect('home') #get user profile my_user_profile = UserProfile.objects.get(user=my_user) user_prompt = createPrompt(my_user_profile, request_body.get('position'), request_body.get('company'), request_body.get('description')) system_prompt = "You are a helpful assistant." #create x using chatgpt url = "https://api.openai.com/v1/chat/completions" headers = { "Authorization": f"Bearer {settings.OPEN_AI_API_KEY}", "Content-Type": "application/json" } # Craft the request payload payload = { "model": "gpt-3.5-turbo", "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": … -
Unique_together doesn't work if a field is null. How to constrain it?
I have a model like this class ProductCode( models.Model): class Meta: unique_together=[('code','customer'), ] customer = models.ForeignKey( 'customers.Customer', models.CASCADE, null=True, blank=True, ) code = models.CharField( max_length = 20) product = models.ForeignKey( Product, models.CASCADE, ) ... The trouble is that if customer is None (DB null) then the constraint is not enforced. It lets me store rows/objects with, say, (code='foo', customer=None) multiple times. I have found this SO post which suggests that the problem is un-fixable for Postgres users. Is there any way to enforce this constraint with the (relatively) new Meta constraints? I am finding the documentation a bit hard to fathom. Or do I have to implement a placeholder customer to attach "default" product codes to? Or, another way would be to prepend a textual representation of customer to code and then just make it unique=True and use __startswith= and __contains lookups where necessary. -
How can I implement basic authentication between Next.JS and DRF using JWT?
I am trying to recode the website for my student club and would need some assistance regarding authentication. I do have a Django Backend setup with all the necessary data (e.g. Member infos, etc.) and would like to display them on the frontend (name + position) and on the Backend (email, phone number, etc.). Now to achieve that I would need basic authentication where I can give out login credentials to the members and they can login (no sign up from the website). Now I am wondering how to do that; coming from Django I would generate a credential pair and the authentication would go via JWT, but I cant find a suitable example (everything is very old). Right now my setup looks like this: Django Backend with JWT Next.JS frontend (typescript, tailwind css) with seperate login page I was looking at next-auth which seems promising but I am afraid that login via Socials is not my usecase. Can anyone provide more information how to setup Django with Next.JS with authentication? Cheers I already tried using Next-Auth with some examples provided on the internet but none of them worked/ were deprecated. -
Django: update data with ajax view (error on data format)
I want to update django data using ajax view but got an error "AttributeError: 'str' object has no attribute 'get'" dealing with format data passed in form in my view. I first serialized data of my form with Jquery and send data using ajax. In my view, I retrieve data (but str format) so when I passe it to my Form, an error is raised. I've tried many, JSON.parse in Jquery and Json.loads in my view and many other thing but nothing works // lock a form $("body").on("click", '.lock', function (event) { var model = $("form").data('model'); var csrfmiddlewaretoken = $("input[name='csrfmiddlewaretoken']").val(); // retrieve ide of form to lock/unlock var ide = $("form").data('ide').toString(); var url = "/ecrf/lock/".concat(ide); var data = $("form").serialize() console.log('serialize data', data) $.ajax({ type: "POST", url: url, data: { csrfmiddlewaretoken: csrfmiddlewaretoken, 'model': model, 'data': data }, dataType: 'json', success: function (response) { console.log('success'); }, }); }); def lock(request,pk): from urllib.parse import parse_qs model = apps.get_model('ecrf', request.POST.get('model')) data = request.POST.get('data') lock_unlock = None obj = get_object_or_404(model, ide = pk) form = SociodemographiqueForm(data=data or None, instance = obj) if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == "POST": if form.is_valid(): form.save() ... return JsonResponse({},status=200) -
django: suit.apps could not be resolved
I'm trying to use the Django Suit, I have downloaded the django v2-dev using pip and added the SuitConfig in the INSTALLED_APPS before django.contrib.admin. However, when I write "from suit.apps import DjangoSuitConfig" I get suit.apps could not be resolved apps.py file ] [settings,py][(https://i.stack.imgur.com/9ajKF.png)] -
How to fix "Permissions Denied" and "No such file or directory" Errors? Using Django and Docker Compose
Permissions Denied for makemigrations command in Django. I typed in the following: docker-compose -f production.yml run --rm django python manage.py makemigrations Then I got the following: PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.9/site-packages/allauth/socialaccount/providers/openid/migrations/0002_auto_20230524_1428.py' So I tried to give permissions by doing the following: sudo chown ec2-user /usr/local/lib/python3.9/site-packages/allauth/socialaccount/providers/openid/migrations/ But then I get the following: chown: cannot access ‘/usr/local/lib/python3.9/site-packages/allauth/socialaccount/providers/openid/migrations/’: No such file or directory So there's no directory to give permissions to? I checked what exists, and there's python3.7 but not python3.9 in the remote server. But I think Django uses Python3.9, I just don't know where it exists? I tried to give permissions to the directory but apparently the directory that contains the migrations doesn't exist. -
django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row')
Upon calling the get_tag_posts method of the Profile model, it is raising the following error: django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row') What about the query is causing this error and what correction should be made in order to resolve this it? authors/models.py class Profile(Model): user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE) def get_tag_posts(self, order_by=None): tags = Tag.objects.filter( question__profile=self ).distinct() questions_with_tag = self.questions.filter( tags__name=OuterRef("name")).only('id') records = tags.annotate( times_posted=Count(Subquery(questions_with_tag)), avg_question_score=Avg("question__score", output_field=IntegerField()) ) if not order_by or order_by not in ['name', 'score']: order_by = "name" if order_by == "name": records = records.order_by(order_by) else: records = records.order_by("-avg_question_score") return { 'records': records, 'title': f"{tags.count()} Tags" } posts/models.py class Tag(Model): name = CharField(unique=True, max_length=25) class Meta: managed = True db_table = "tag" def __str__(self): return f"{self.name}" def get_absolute_url(self): return f"/questions/posted/{self.name}" class Post(Model): body = TextField() date = DateTimeField(default=timezone.now) comment = ForeignKey('Comment', on_delete=CASCADE, null=True) profile = ForeignKey( 'authors.Profile', on_delete=SET_NULL, null=True, related_name='%(class)ss', related_query_name="%(class)s" ) vote = GenericRelation( 'Vote', related_query_name="%(class)s" ) score = IntegerField(default=0) class Meta: abstract = True managed = True class Question(Post): title = CharField( max_length=80, unique_for_date="date", help_text="Concisely state the problem you're having", error_messages={ "max_length": "The title of your question is too long" } ) tags = ManyToManyField( 'Tag', related_name="questions", related_query_name="question" ) views = IntegerField(default=0) visible = BooleanField(default=True) … -
How to return existing matching record for Django CreateView
I use a regular generic.edit.CreateView of Django to create an object according to user input. The MyModel has an UniqueConstrait so the creation would fail if the new object happens to match an existing one. However, instead of telling users that creation fails due to duplicate records, I would like to simply return the existing object since this is what users want. I tried to override def save(self, commit=True): return MyModel.get_or_create(value=self.cleaned_data['value'])[0] but this does not work because form._post_clean will call form.instance.full_clean with its default validate_constraints=True, so an error will return during form validation. Essentially I am looking for a GetOrCreateView but I am not sure what is a clean way to achieve this (other than maybe overriding form._full_clean). Note that I am not looking for a UpdateView because we do not know in advance which existing object will be returned.