Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker postgres role does not exist
I am using postgres with docker and having trouble with it. I successfully docker-compose up --build When I run below command it works fine. psql starts with my_username user as expected. I can see my database, \l, \dt commands works ok. docker-compose exec db psql --username=my_username --dbname=my_database But when I run below commands I get error role “postgres” does not exist, Additionally \l, \dt not works, even psql command not works docker exec -it my_db_container_1 bash su - postgres createuser --createdb --password new_user How can I get it right in the second case? What is going wrong? I am confused docker-compose.yml version: "3.9" services: #### other services #### db: image: postgres:latest restart: always environment: POSTGRES_DB: my_database POSTGRES_USER: my_username POSTGRES_PASSWORD: my_password ports: - 5432 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: -
django.contrib.admin.sites.AlreadyRegistered: The model Ingredients is already registered with
I was trying to register the offer model, but it instead of throwing me this error now , help needed , thanks in advance from django.contrib import admin from django.contrib.admin import ModelAdmin from menus.models import Category, MenuItem, Ingredients,Offer # Register your models here. class CategoryAdmin(admin.ModelAdmin): fields = ['name', 'description'] list_display = ['name', 'description', 'uri_name'] class MenuItemAdmin(ModelAdmin): list_display = ('category', 'item_name', 'description', 'price') class IngredientsAdmin(admin.ModelAdmin): list_display = ('name', 'item',) admin.site.register(Offer) admin.site.register(Category, CategoryAdmin) admin.site.register(MenuItem, MenuItemAdmin) admin.site.register(Ingredients, IngredientsAdmin) error in register raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model Ingredients is already registered with 'menus.IngredientsAdmin'. -
Django messages not showing in my html template
I am trying show success message after objects delete from my list view page. here is my code: #this is the delete view class DeleteNoti(DeleteView): model = Notifications def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['messages'] = messages.add_message(self.request, messages.INFO, 'Notification deleted') return data success_url = reverse_lazy('notifications:notify') This is my html page where I am listing my all objects and added delete functionality: #using this for showing success message {% if messages %} <ul class="messages"> {% for message in messages %} <div class="alert alert-success" role="alert"> <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </div> </ul> {% endif %} #this code deleting my objects but I am not seeing any message after successful delete. <form method="POST" action="{%url 'notifications:delete-noti' i.pk%}"> {% csrf_token %} <button type="submit" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close"></form> -
Overwrite of the save method to ensure integrity in database doesn't work
A user always has one default dashboard for each company they are associated with. They can add new dashboards, as soon as they set one as the default, the other one gets reset. To achieve this I tried overwriting the save method on the Dashboard model: def save(self, *args, **kwargs): if self.is_default: for dash in Dashboard.objects.filter(user=self.user, company=self.company): if dash.is_default: dash.is_default = False dash.save() else: if Dashboard.objects.filter(user=self.user, company=self.company, is_default=True).exclude(id=self.id).count() == 1: raise ValidationError( 'There has to be a default dashboard per company for this user.') return super().save(*args, **kwargs) The code above doesn't work, as it lets me set a dashboard with is_default=False and doesn't raise the ValidationError, if the criteria isn't fulfilled. -
QuerySet Manager django problem with 'objects'
I need to create 2 different ModelManager which inherits from my own Manager 'models.QuerySet' I created : class ActiveObjectsQuerySet(models.QuerySet): def filter_active(self): return self.filter(status=Book.Statuses.ACTIVE) class AllObjectsQuerySet(models.QuerySet): def filter_reissued(self): return self.filter(status=Book.Statuses.REISSUED) def filter_reviewed(self): return self.filter(status=Book.Statuses.ON_REVIEW) and this one: objects = ActiveObjectsQuerySet.as_manager() objects = AllObjectsQuerySet.as_manager() I have a question - does the objects for different Managers must to have other name or the same name 'objects' ?Because my code does not work(((what I need to do with the names 'objects'?Please help me -
Django saving ManyToManyField gives error: Field 'id' expected a number but got 'str'
I'm trying to use a ManyToManyField to create a model attribute with a set of options (instances of the m2m model). When I go to save the model in my ModelForm, save_m2m() gives an error saying that Field 'id' expected a number but got 'T'. Here is my code: Model: class Listing(models.Model): idtag = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) published = models.DateTimeField("Date Published", default=timezone.now) description = models.TextField() price = models.PositiveBigIntegerField() crypto = models.ManyToManyField(Choices) location = models.CharField(max_length=100) only_location = models.BooleanField(default=False) tags = TaggableManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('main:listingdetails', kwargs={'pk': self.pk}) View: @login_required def createview(request): if request.method == "POST": creationform = ListingForm(request.POST, author=request.user) if creationform.is_valid(): creationform.save(commit=False) creationform.save_m2m() listing = creationform.instance messages.success(request, "New Listing Created") return redirect(reverse('main:listingdetails', kwargs={'pk': listing.idtag})) else: messages.error(request, 'Please correct the error below.') creationform = ListingForm return render(request, "main/createlisting.html", context={"creationform":creationform}) Form: class ListingForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.author = kwargs.pop('author', None) super(ListingForm, self).__init__(*args, **kwargs) cryptoList = (("ETH", "Ethereum"), ("TRP", "TroupeCoin")) crypto = forms.ChoiceField(choices=cryptoList) def save(self, commit=True): listing = super(ListingForm, self).save(commit=False) listing.author = self.author if commit: listing.save() class Meta: model = Listing fields = ('title', 'description', 'price', 'crypto', 'tags') Traceback: The above exception (invalid literal for int() with base 10: 'T') was the … -
Why I'm getting this Error TemplateDoesNotExist at /konfigure/index.html
I'm getting this error when I'm trying to go to the configuration section of my site. This is my folder structure: [[1]: https://i.stack.imgur.com/DhV7A.png] Here's the code: Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'konfigurator', 'upcservice', 'cloudinary', ] -
tables automatically added to database when creating custom user model in django
I created custon user model extending AbstractUser. But when making migrations, many tables were added to postgresal, i have only two models. i named my customuser : CustomUser and the other model Offers. These tables were found in postgresql: api_customuser api_customuser_groups api_customuser_user_permissions api_offers, auth_group, auth_group_permissions, auth_permission, django_admin.log and others Note that my django app is named : api. Is it normal ? -
Which is better: MongoDB vs PostgreSQL for storing JSON data
I am creating a Django project. The core feature of this project is to create dynamic forms, then to fill these forms and finally to visualize this informations using some BI tools. In addition to creating/storing dynamic forms information, user will be able to create relations between forms (like the foreign keys in the relational databases) on specific fields. I am planning to store these dynamic forms aw JSON fields in the database. consequently, I am wondering whether it would be a better to choice to choose PostgreSQL or MongoDB to store the JSON data. Please note that the main feature of my app is to insert/update/read these JSON data at the first place. Next, A BI tool will be implemented (based on these JSON data) to visualize the data. I already saw multiple comparison between MongoDB and PostgreSQL for storing JSON data and it seems to be remain an open question. What do yo think? -
I'd like to modify the JavaScript code to meet the conditions [closed]
I am a student who is learning web programming. It's just that I added functionality to the program, so it's not saved in DB. Above is saved, but features have not been added, below is added, but not saved to DB. I think it's because of Select. If you correct the code below, we will adopt it right away. I'd like to supplement this content so desperately. I'm looking for an expert who can solve this code that hasn't been solved after two weeks of hanging on. Thank you for reading the long question. Existing code stored in DB: <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="value_code" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="value_code" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> </div> Code not saved : <style> * {padding: 0; margin: … -
(DJANGO) Storing Multiple data from html forms to the database
I am create a quiz app and i have some value for every radio Option, and i want to store the question,option user have selected and the optionvalue. Below is the model for Questions where i have stored the Question from where i need to fetch the questions to show to the user. models.py class modelStrategy(models.Model): domainStrategy = models.CharField( max_length=20, default="Strategy", blank=True) dateStrategy = models.DateField(auto_now_add=True) priorityStrategy = models.IntegerField() questionsToAddStrategy = models.CharField(max_length=256) questionType = models.CharField(max_length = 20,choices=QUESTION_CHOICE,null=True, blank=True) question_text = models.CharField(max_length=200,null=True, blank=True) OptionsOneStrategy = models.CharField(max_length=120, null=True, blank=True) OptionsOneValueStrategy = models.IntegerField(null=True, blank=True) OptionsTwoStrategy = models.CharField(max_length=120, null=True, blank=True) OptionsTwoValueStrategy = models.IntegerField( null=True, blank=True) OptionsThreeStrategy = models.CharField( max_length=120, null=True, blank=True) OptionsThreeValueStrategy = models.IntegerField(null=True, blank=True) OptionsFourStrategy = models.CharField( max_length=120, null=True, blank=True) OptionsFourValueStrategy = models.IntegerField(null=True, blank=True) OptionsFiveStrategy = models.CharField( max_length=120, null=True, blank=True) OptionsFiveValueStrategy = models.IntegerField(null=True, blank=True) OptionsSixStrategy = models.CharField( max_length=120, null=True, blank=True) OptionsSixValueStrategy = models.IntegerField(null=True, blank=True) here is the views.py file def chnageQuesStra(request): if request.method == "POST": saveans = modelAnswer() saveans.questionsToAddStrategy = request.POST.get("Question") saveans.OptionsStrategy = request.POST.get('option') questionsToAddStrategy = request.POST.get("Question") saveans.save() mod = modelStrategy.objects.all() paginator = Paginator(mod,1) try: page = int(request.GET.get('page','1')) except: page =1 try: questions = paginator.page(page) except(EmptyPage,InvalidPage): questions = paginator.page(paginator.num_pages) context = { "mod":mod, "questions":questions, } return render(request,'Questions.html',context=context) here is the html code were i … -
How to fix: ProgrammingErrorsAlreadyExists'django_content_type'
When I run the server it gives this message on console: "You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them." When I try to run python manage.py migrate. It shows this message at the bottom: "[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]There is already an object named 'django_content_type' in the database." -
Unable to add values at features in django admin panel
I am new in Django and now I am working with manipulation of database in django admin panel. While playing with features I am unable to add values in features. There is no key and after saving it leaves empty object. I am using django 2.2.5. Click for the image Here are my codes models.py from django.db import models class Feature(models.Model): name: models.CharField(max_length=20) age: models.IntegerField(max_length=3) sex: models.CharField(max_length=5) point: models.CharField(max_length=5) partner_name: models.CharField(max_length=20) relation: models.CharField(max_length=20) partner_age: models.IntegerField(max_length=3) partner_sex: models.CharField(max_length=5) partner_point: models.CharField(max_length=5) description: models.CharField(max_length=500) partner_img: models.CharField(max_length=100) admin.py from django.contrib import admin from .models import Feature # Register your models here. admin.site.register(Feature) urls.py import myapp from django.contrib import admin from django.urls import path, include admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), path("", include("myapp.urls")) ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] -
getting multiple countdown timers from querysets using django models and javascript
I really don't know how to push on with this, the idea is an investment platform where the user can have multiple investments and each investment has a due date enter image description here this image shows that when I try to query the countdown timer it just shows for the first query set and it picks the new query added to the model query set <script> let timer = new Date({{amt.timer|date:'U'}}*1000) time = new Date(timer).getTime() newbox = document.getElementById('box') var interval = setInterval(() => { const now = new Date().getTime() const diff = time - now console.log(` this is testing diff ${diff}`) console.log(` this is testing ooo ${time}`) console.log(` this is testing now ${now}`) const d = Math.floor(diff / (1000 * 60 * 60 * 24) ) const h = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const s = Math.floor((diff % (1000 * 60)) / 1000); newbox.innerHTML = `${d} days ${h} hours ${m} minutes ${s} seconds` if (diff < 0) { clearInterval(interval) } {#console.log(time)#} {#console.log(diff)#} {#console.log('hello')#} }, 1000) </script> this code is in the forloop. thanks, I … -
Get Django Custom user model listed under admin app `Authentication and Authorization`
Note my question is similar to this one, however that answer recommend not calling the customised user model User, whereas the official docs and this issue do. I created a custom User model in an app called plug: plug/models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): """ Requirements: - Must be defined in models.py, due to the way settings.AUTH_USER_MODEL is defined - Must not be called 'User', or else can't list it in same table """ is_hamster = models.BooleanField(default=False) is_superhero = models.BooleanField(default=False) is_pogo_stick = models.BooleanField(default=False) class Meta: # app_label = 'auth' # <-- This doesnt work db_table = 'auth_user' settings.py file set accordingly: AUTH_USER_MODEL = 'plug.User' plug/admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model @admin.register(get_user_model()) class UserAdmin(UserAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'is_hamste', 'is_superhero', 'is_pogo_stick') list_display_links = list_display fieldsets = UserAdmin.fieldsets + ( ('Leasing User Role', {'fields': ('is_hamste', 'is_superhero', 'is_pogo_stick')}), ) All is good except in the admin interface the custom user is listed under the heading Plug instead of under Authentication and Authorization (where Users used to be listed, along with Groups). I tried setting app_label = 'auth' in the meta of the custom user model, however then it fails … -
Store data just for a single session in Django?
I am currently creating a website with Django and I came across the following question: I want to store data, the user enters (a string (e.g. a name or his age)), BUT it must be "deleted" when the same user enters the website again after closing it so is should only be saved for the current session. So I read about cookies but they actually DO store the data of a session to be used again in the next. So does anyone know a way to store data for a single session in Django? Thanks in advance -
How to i get session value userid in adddomainwiseprojects - django(using inline formset method)
Here i have attached views.py where add_projectdomain fields are added by importing models, here how can i get the loginid i.e. session key(userid) (as i have got in company_details view by using reuest.session.get method) in Add_domainwise projects form and save it. views.py from django.shortcuts import render,HttpResponse,redirect from .models import Add_domainwise_projects, Company_details, Country_master, State_master, City_master, Domain_master, Company_testimonials from .models import tbNewUser from django.contrib import messages from .forms import Add_domainwise_projectsForm from django.forms import inlineformset_factory, HiddenInput def logout(request): try: del request.session['userid'] except: return render(request, 'indexpage.html') return render(request, 'indexpage.html') def loginpage(request): if request.method == 'POST': try: Userdetails = tbNewUser.objects.get( userid=request.POST['userid'], password=request.POST['password']) print("Username=", Userdetails) request.session['userid'] = Userdetails.userid return render(request, 'indexpage.html') except tbNewUser.DoesNotExist as e: messages.success(request, 'Login ID or Password is Invalid..!') return render(request, 'Login.html') def Userreg(request): if request.method == 'POST': username = request.POST["username"] userid = request.POST['userid'] password = request.POST['password'] Alternatemail = request.POST['Alternatemail'] phone = request.POST['phone'] tbNewUser(username=username, userid=userid, password=password, Alternatemail=Alternatemail, phone=phone).save() messages.success(request, 'The userid' + request.POST['userid']+" is registered successfully") return render(request, 'Registration.html') else: return render(request, 'Registration.html') print("not saved") def indexpage(request): companies=Company_details.objects.all() context={'companies':companies} return render(request, 'indexpage.html',context) def add_country(request): if request.method == "POST": countryname = request.POST.get("countryname") Country_master.objects.create( countryname=countryname ) return render(request, "add_country.html", {"msg": 'Country- '+request.POST['countryname'] + 'Added!' }) else: return render(request, "add_country.html") def add_state(request): if request.method == "POST": … -
Django slow inner join on a table with more than 10 million records
I am trying to count the number of visitor_pages for a specific dealer in a certain amount of time. I would share the raw sql query that I have obtained from django debug toolbar. SELECT COUNT(*) AS `__count` FROM `visitor_page` INNER JOIN `dealer_visitors` ON (`visitor_page`.`dealer_visitor_id` = `dealer_visitors`.`id`) WHERE (`visitor_page`.`date_time` BETWEEN '2021-02-01 05:51:00' AND '2021-03-21 05:50:00' AND `dealer_visitors`.`dealer_id` = 15) The issue is that I have more than 13 million records in the visitor_pages table and about 1.5 million records in the dealer_visitor table. I am thinking of using a materialized view but before attempting that, I would really appreciate suggestions on how I could improve this query. -
mock or override values in apps.py (Django) for testing
Typically I'd set a value in settings.py and then use @override_settings in tests to override it. Is there any similar mechanism that exists for overriding settings in apps.py when using app_config? For instance # apps.py class MyConfig(AppConfig): SOME_VAR = "SOME_VAR" # some .py file from django.apps import apps apps.get_app_config('some_app').SOME_VAR # some test.py # How to change the value that apps.get_app_config('some_app').SOME_VAR returns? It's strange this isn't covered in the docs as it feels this would be a common use case or maybe I'm missing something? Thanks, -
pagination does not work for numbers in between and also for reverse in django
I am filtering my data, and also applying paginator, I have found some solution and I used it but it is working only for the next button and not for previous and button numbers in between i.e. for {{i}} (Django, python) this is template_tag file myapp_extra.py from django import template register = template.Library() @register.simple_tag def my_url(value, field_name, urlencode=None): url = '?{}={}'.format(field_name, value) if urlencode: querystring = urlencode.split('&') filterd_querystring = filter(lambda p: p.split('=')[0]!=field_name, querystring) encoded_querystring = '&'.join(filterd_querystring) url = '{}&{}'.format(url, encoded_querystring) return url in my html {% load myapp_extra %} <other code> <nav> <ul class="pagination rounded-separated justify-content-center" style="float: right; margin-top: 1%;"> {% if employees_attendance_list.has_previous %} <li class="page-item"><a class="page-link" href="{% my_url employees_attendance_list.previous_page_number 'page' request.GET.urlencode }"><i class="mdi mdi-chevron-left"></i></a></li> {% else %} <li class="disabled"></li> {% endif %} {% for i in employees_attendance_list.paginator.page_range %} {% if employees_attendance_list.number == i %} <li class="page-item active"><a class="page-link" >{{ i }}</a></li> {% else %} <li class="page-item"><a class="page-link" href="{% my_url i 'page' request.GET.urlencode}">{{ i }}</a></li> {% endif %} {% endfor %} {% if employees_attendance_list.has_next %} <li class="page-item"><a class="page-link" href="{% my_url employees_attendance_list.next_page_number 'page' request.GET.urlencode %}"><i class="mdi mdi-chevron-right"></i></a></li> {% else %} <li class="disabled"></li> {% endif %} </ul> </nav> in views page = request.GET.get('page', 1) paginator = Paginator(employees_attendance, settings.PAGE_LIMIT) try: employees_attendance_list = paginator.page(page) … -
Django testing how to make a request as logged in user?
In Django tests, I want to log in and make a request. Here the code def test_something(self): self.client.login(email=EMAIL, password=PASSWORD) response = self.client.get(reverse_lazy("my_releases")) self.assertEqual(response, 200) But the code doesn't work and returns AttributeError: 'AnonymousUser' object has no attribute 'profile' How to make request in test as logged in user? -
File deletion when cloning a model that contains an ImageField
When I save() a model that contains an ImageField, the post_save signal of the model base deletes the file that was previously associated with the ImageField which is fair enough because the file has changed to a new value. However, if I've cloned the model, i.e. loaded an object from the db, set it's pk to None, set it's ImageField to a new value and then done a save(), I don't want it to delete the original file because it's still in use by the object that was cloned. item = Item.objects.get(id=kwargs['pk']) item.pk = None item.thumbnail = <new image> item.save() #<--causes the original Item's thumbnail file to be deleted This feels like its such a normal procedure that there should be a pattern for doing it without overriding signals but I'm damned if I can see it. Can anyone point me in the right direction please. -
Is It possible to listen to Rest API Endpoint using django channels?
Goal is to send the serialized data of the created object of POST Method! Request will come from Android/IOS app built with Flutter/Dart I am trying to use Django Channels Rest Framework. But I am not sure if it is gonna work or not! -
Angular app keeps saying message does not exist
I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/ However, I'm trying to run the app to create the chat view but it keeps saying 'messages' does not exist at the point marked 'this point' in the code. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { MessageResponse, Channel } from 'stream-chat'; import { StreamService } from '../stream.service'; import { StateService } from '../state.service'; declare const feather: any; @Component({ selector: 'app-chat', templateUrl: './chat.component.html', styleUrls: ['./chat.component.scss'], }) export class ChatComponent implements OnInit { constructor( public streamService: StreamService, private stateService: StateService, private router: Router ) {} messages: MessageResponse[] = []; message = ''; channel!: Channel; async sendMessage() { if (this.message) { try { await this.channel.sendMessage({ text: this.message, }); this.message = ''; } catch (err) { console.log(err); } } } getClasses(userId: string): { outgoing: boolean; incoming: boolean } { const userIdMatches = userId === this.streamService.currentUser.messages.id; (this point) return { outgoing: userIdMatches, incoming: !userIdMatches, }; } } -
how to show success message on keyclock page in django?
{% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{message.tags}}" {% endif %}> <i class="bi bi-exclamation-triangle-fill"></i> {{ message }} </li> {% endfor %} </ul> {% endif %} I want to show this message on keycloak page. it's server is different from our Django project now how can show success message displaying on keyclock page The view returns success and error message response = requests.post(reset_url, data=payload, headers=headers) if response.status_code == 200 and response.json()["statuscode"] == "E_SUCC": messages.success(request,"You should receive an email with further instructions") else: messages.error(request,"Email not found.")