Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ManyToMany in Form_valid
I have 2 models that are related to ManytoMany class Prestaciones(TimeStampedModel): nombre = models.CharField('Prestanciónes', max_length=35) prestacion = models.ManyToManyField(PrestacionIndi) turno = models.ForeignKey(Turno, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) activo = models.BooleanField(default=True) class PrestacionIndi(TimeStampedModel): nombre = models.CharField('Prestanción', max_length=35) num_dias = models.IntegerField('Dias',) user = models.ForeignKey(User, on_delete=models.PROTECT) activo = models.BooleanField(default=True) View: class PrestacionesCreateview(FormView): template_name = 'admins/form_prestaciones.html' form_class = PrestacionesForm success_url = reverse_lazy('admins_app:prestaciones') def form_valid(self, form): nombre = form.cleaned_data['nombre'] prestacion = form.cleaned_data['prestacion'] turno = form.cleaned_data['turno'] user = self.request.user obj, created = Prestaciones.objects.get_or_create( nombre = nombre, user = user, prestacion = prestacion, turno = turno ) return super(PrestacionesCreateview, self).form_valid(form) When making a save, it marks an error since it cannot save several values. I think my problem would be in the form_valid area since it is only receiving a value and it is not iterating the values -
How to make my Django API public, which is connected to MYSQL database?
The problem is I have connected my Django API to MYSQL workbench, but it is only accessible in my localhost. Methods I have tried: Forwarding a port and running my server with "python manage.py runserver 0.0.0.0:3000", which worked, and the API was made public in my another Django API project without MYSQL connection but not working in the one connected to MYSQL. I hosted my Django API in PythonAnywhere. Now my API became public, but I could not connect my Django API with MYSQL. Please help me with it. Thanks in advance -
WARNINGS: ?: (mysql.W002)
I'm new to django, just wanted to change to MySQL databases, but this warning keeps how up even though I have already added the code for it. My setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "mysql_database", "USER": "root", "PASSWORD": "", "OPTION": { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1", 'charset': 'utf8mb4', "autocommit": True, } } } The warning WARNINGS: ?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.1/ref/databases/#mysql-sql-mode Have tried resetting and migrating a couple of times, and it didn't work. -
After an upgrade from Django 1.11 to Django 3.1 django admin shows list of models on top of internal items
After an upgrade from Django 1.11 (python2.7) to Django 3.1 (python3.6) on Centos7, django admin still shows the list of models on top of the page, above the list of items in this model. Before the upgrade, the admin showed everything correctly: you see a list, you enter an item and see a screen related to this item, no more lists. Please see the related screenshots: Please advise how to solve this. -
Django Modelforms: how to show a select for a CharField?
I'm using ModelForms in Django to create my form. This works well. However, there is a field that is a charfield in the database, but for a particular form I want to restrict the options that users can enter to a list of specific items - ideally shown in a <select>. What would be the right way to do this? Here is my code: form = ModelForm(request.POST or None, instance=info) In my models: class Street(models.Model): name = models.CharField(max_length=255) I have tried the following: from django import forms CHOICES = [('1', 'First'), ('2', 'Second')] choice_field = forms.ChoiceField(widget=forms.Select, choices=CHOICES) form.fields["street"].widget = choice_field Which gives this error: 'ChoiceField' object has no attribute 'attrs' -
Django Template Is Not Updating the Selected Option
I have been working on this template where I need to show the options (showing the list of companies using for loop) for selection. <select id="company_id" name="company_id"> <option selected="selected">(없음)</option> {% for company in company_list %} <option value="{{company.id}}"> {{company.name}} </option> {% endfor %} </select> On the template it looks like this: the actual template default option the dropdown options Let's say I picked the 6th option (2nd from the bottom). I want the default option to be changed VISUALLY when I hide the dropdown, clicking somewhere else. However, the selected option does not show visually. It goes back to that very first option Strangely, however, when I click on the selection to view the dropdown list, I see that the one I clicked is selected, though it is vague. The 6th option is colored whereas unselected ones are black Is there any way to make it show the one selected? My user complains that it is very confusing to keeping seeing the first option only even after selecting something else. One thing I tried is getting rid of 'selected="selected"' snippet like so: <select id="company_id" name="company_id"> <option>(없음)</option> {% for company in company_list %} <option value="{{company.id}}"> {{company.name}} </option> {% endfor %} </select> However, … -
Django Admin how to show ID of Items in List
Here is what i see in my Django Admin: The model Topic has 4 fields in it. class TopicModel(models.Model): strid = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200, unique=True) description = models.TextField() code = models.TextField() It's not convenient to see topics list as a TopicModel object (1) TopicModel object (2) TopicModel object (3) Is there a setup to show fields values (for example 'name') in the list like: TopicModel name1 TopicModel name2 TopicModel name3 I'm sure should be some setup for this in Django, Please notify me if it's possible? -
Django/DRF - minimize DB lookups in foreign keys
Assume the following model realtionships: class Country(Model): name = CharField(max_length=10) class Company(Model): name = CharField(max_length=10) country = ForeignKeyField(to=Country, on_delete=CASCADE) class Department(Model): name = CharField(max_length=10) company = ForeignKeyField(to=Company, on_delete=CASCADE) class User(Model): name = CharField(max_length=10) department = ForeignKeyField(to=Department, on_delete=CASCADE) There is a requirement to show User's country. In DRF I acess the field using following Serializer: class UserSerializer(ModelSerializer): country = CountrySerializer( source='department.company.country' ) class Meta: model = User fields = '__all__' Which leads to an awful lot of database requests (let's take 1000 Users in a list view - for each of them there is a lookup on department->Company->Country -> 3 Lookup queries to database) The requests take quite long for ListViews with many users. My possible solutions so far: Create a country field on the user model that caches the country object. Then create a periodic job that updates the cache (otherwise the first request would take awfully long) -> Downside is higher Complexity, running async jobs, ... Create a country field on the user model that is a database json field that stores the country. Create signal listeners on user, department, company save Method to update the field. -> Leads to great complexity due to signal listeners and spaghetti code … -
How to make celery beat task with django work on all objects rather than just a single object?
I am trying to delete the expired receipts through a scheduler task, but I am facing a problem as each time the function runs, it deletes only 1 object even though there are a lot more. How can I change the code I have to make sure that it deletes all the objects which has passed its expiry date, when the scheduler runs every 60 mins? @periodic_task(run_every=crontab(minute='*/60')) def delete_expired_receipts(): receipts = Receipt.objects.all() for receipt in receipts: if receipt.expiry_date <= timezone.now(): receipt.delete() return "deleted the receipts at {}".format(timezone.now()) return "No receipts" Thanks -
Custom id AutoField in Django model
i want create a custom field with AutoField description: Code generated by the system is increasing gradually, the code consists of 5 digits, there are no 2 identical codes. For example: 00001, 00002 this is my code : class Supplier(models.Model): code = models.AutoField(primary_key=True, max_length=5, blank=False, null=False) name = models.CharField(max_length=200, blank=False, null=False) phone = models.CharField(max_length=11, unique=True, validators=[len_phone]) email = models.EmailField(blank=True, null=True, unique=True) address = models.CharField(max_length=200, blank=False, null=False) -
How to test an api, making use of a django view function
I currently have a Django API mixed with some GRPC stuff. The API makes use of a Django view function @require_GET def django_view_fn(): pass within the api class API: def api_funct(self): result = def django_view_fn return result.pb everything works well as it is right now during normal operation, eg via postman. The only problem I have is, the function doesn't work during Django test/TestCase. It returns a 405 as the response, instead of the expected response from the view function. it only works if I comment out the @require_GET on the view function decorator in the view file -
Django - for each record in database, multiply two values and find the sum
I'm learning Python and Django currently... I have a database with the following fields: ID, amount, number I want to multiply (amount * number) for each record in database, to assign result to variables, and after that to find a sum of all variables. For example: Database: 100 14 50 12 80 10 60 15 . . . etc I want to achieve this: a = 100 * 14 b = 50 * 12 c = 80 * 10 d = 60 * 15 . . .etc and after that, to find a SUM (a+b+c+d....etc), and to display that value in my template. What I have done: VIEWS: def report(request): prof = Test.objects.all() response = TemplateResponse(request,'report.html', {'all': prof}) return response MODELS: class Test(models.Model): number1= models.DecimalField(max_digits=5, decimal_places=2) amount= models.IntegerField() def __str__(self): return self.name @property def profit(self): a = self.amount * self.number1 return a TEMPLATE {% for games in all %} {{ games.profit }} <br> {% endfor %} The code above is displaying the multiplied results for each record in database, but I do not know how to find the SUM of all those new values? Any help will be appriciated. Thanks -
AttributeError at /8/1/ This QueryDict instance is immutable in django rating app
I am using start-rating library in my django application then i am getting this error. Please anyone tell me how to solve it. --------------------------------------------------------- this is my model.py in testapp application in my project class Test(models.Model): name = models.ForeignKey(CustomUser,on_delete=models.CASCADE) subject = models.CharField(max_length=30) ratings = GenericRelation(Rating, related_query_name='test') class TestCreate(LoginRequiredMixin,CreateView): login_url = '/login/' model = Test fields = '__all__' success_url = '/' template_name = 'testapp/test.html' class TestList(ListView): model = Test template_name = 'testapp/test_list.html' class TestDetails(DetailView): model = Test template_name = 'testapp/test_details.html' Here my test_details.html file where i am getting error <ul> <li>{{ object.subject }}</li> {% ratings object %} </ul> please any one tell me solution? please tell me how to solv -
Facing issue to connect to SQLLITE table using raw sql
I'm trying to connect to SQLite table using rawsql querry but unsuccessfully . Here is my model : class CsqAgentReport(models.Model): nodeid_sessionid_sequenceno = models.TextField(db_column='NodeID-SessionID-SequenceNo', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. callstarttime = models.TextField(db_column='CallStartTime', blank=True, null=True) # Field name made lowercase. callendtime = models.TextField(db_column='CallEndTime', blank=True, null=True) # Field name made lowercase. contactdisposition = models.IntegerField(db_column='ContactDisposition', blank=True, null=True) # Field name made lowercase. originatordn_callingnumber_field = models.IntegerField(db_column='OriginatorDN(CallingNumber)', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'. destinationdn = models.IntegerField(db_column='DestinationDN', blank=True, null=True) # Field name made lowercase. callednumber = models.IntegerField(db_column='CalledNumber', blank=True, null=True) # Field name made lowercase. pivotoriginatordn = models.TextField(db_column='PivotOriginatorDN', blank=True, null=True) # Field name made lowercase. pivotcallednumber = models.TextField(db_column='PivotCalledNumber', blank=True, null=True) # Field name made lowercase. csqnames = models.TextField(db_column='CSQNames', blank=True, null=True) # Field name made lowercase. queuetime = models.TextField(db_column='QueueTime', blank=True, null=True) # Field name made lowercase. agentname = models.TextField(db_column='AgentName', blank=True, null=True) # Field name made lowercase. ringtime = models.TextField(db_column='RingTime', blank=True, null=True) # Field name made lowercase. talktime = models.TextField(db_column='TalkTime', blank=True, null=True) # Field name made lowercase. worktime = models.TextField(db_column='WorkTime', blank=True, null=True) # Field name made lowercase. nomcsq = models.TextField(db_column='NomCSQ', blank=True, null=True) # Field name made lowercase. idunique … -
Django, download button instead of downloading image is redirecting to source url
I'm trying to download an image from an AWS storage on click. But when I use the image URL as my href it just redirects to that URL instead of downloading. Of course, I am using the download attribute. I am using Django Template and AWS S3 for storage. Here is my code:- index.html <a download href="{{ portfolio.file.url }}" title="Download" target="_blank"> <i class='bx bxs-download pl-2'></i> </a> views.py def index(request): portfolio = Image.objects.all() context = {"portfolio": portfolio} return render(request, "index.html", context) -
How to access the form variable in FormView
I can access the "form" variable in function based view like: if form.is_valid(): async_mailer.delay(from_address, **form**, None) But When I converted this function based view to class based view and tried to access the variable then I failed. Error is :EncodeError: Can't pickle <type 'function'>: attribute lookup builtin.function failed What I am tring: class MyForm(forms.form): name = form.... reply_to = forms... def save(self,*args,**kwargs): async_mailer.delay(from_address, self , None) I also tried self.form,self.instance but this does not works. -
Does django skip remaining items from the list sent to bulk_update if number of items cross the batch_size?
I was running a data import program in a table and the data I had was nearly one million. So, I went with Django bulk_create and bulk_udpate. I've put a batch_size=500 in the update. Now, what my concern is that, if the list of objects contains more data than the batch_size, does Django throw them away or iteratively insert in batches to the database? I saw some of the data are updated in the table but some are not. -
Losing data from basetemplateview
I have base template view with some data from models which is stored in context. So this template is being used everywhere, when we do post request in from other view I am not able to see the data that is being fetched from models in basetemplateview get_context_data(). class BaseTemplateView(TemplateView): template_name = 'base.html' def get_context_data(self, **kwargs): context['info'] = models.Info.objects.get(id=1) return context class TesView(BaseTemplateView): template_name = 'test.html' form = forms.TestForm def post(self, request, *args, **kwargs): try: c={} c.update(csrf(request)) form = forms.TestForm(request.POST) if not form.is_valid(): variables = {'form': form } messages.error(request, 'Invalid data in form') return render(request, self.template_name, variables ) else: from_date = str(form.cleaned_data['from_date']) to_date = str(form.cleaned_data['to_date']) data = models.Logs.objects.all() if not data: variables = {'form': form } messages.info(request, 'No data found') return render(request, self.template_name, variables) else: data_render = {'data':data, 'title':'Logs', 'form': form} return render(request,self.template_name,data_render) except Exception, exp: logger.error("Logs failed") logger.exception(exp) def get_context_data(self, **kwargs): context = super(TestView, self).get_context_data(**kwargs) context['title'] = 'Logs' context['data'] = models.SystemLogs.objects.filter(Q(ts__range=(from_date,to_date))) context['form'] = self.form return context I am getting data of basetemplateview in testview get request, but for post request i am not able to get data of basetemplateview. -
Check if event target is a file or a value
So basically what my question originates from is me trying to upload an image using a class based react component but I'm having trouble because image is event.target.files whereas other fields I have such as name and title are event.target.values. So far my state and setState look like this. state = { name: '', title: '', caption: '', image: '' } onChange = e => { // I think conditional will go here this.setState({ [e.target.name]: e.target.value }) } How could I create a conditional which checks whether the event.target is a value or a file? Another side question. Since the image is a file and not a value is my state set up correctly? -
Pleae help me solve this issue I deployed my app in heroku
This is the link to the error https://dpaste.com/EC8JPPZTD#wrap -
Role "your_db_user" does not exist
I try to connect my django application and postgres. There is my settings.py file: ... DATABASES = { "default": { "ENGINE": os.environ.get("DB_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("DB_NAME", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("DB_USER", "user"), "PASSWORD": os.environ.get("DB_PASSWORD", "your_db_password"), "HOST": os.environ.get("DB_HOST", "your_db_name"), "PORT": os.environ.get("DB_PORT", "5432"), } } ... There is my envs: DB_ENGINE=django.db.backends.postgresql DB_USER=your_db_user DB_PASSWORD=your_db_password DB_NAME=your_db_name DB_HOST=0.0.0.0 DB_PORT=5432 There is my docker image: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 env_file: - envs/.env.local environment: - POSTGRES_USER=your_db_user - POSTGRES_PASSWORD=your_db_password - POSTGRES_DB=your_db_name Django application logs: django.db.utils.OperationalError: FATAL: password authentication failed for user "your_db_user" pg logs: Role "your_db_user" does not exist. Which problem can be? I can't suppose any problem with it -
Image from ModelForm not being saved
I have a Pgae model in wagtail that is holding an ImageField: from django.conf import settings from wagtail.users.models import upload_avatar_to from django.utils.translation import gettext_lazy as _ class ProfilePage(Page): avatar = models.ImageField( # Also updated from user.wagtail_userprofile.avatar verbose_name=_("profile picture"), upload_to=upload_avatar_to, blank=True, ) intro = RichTextField( blank=True, null=True, verbose_name=_("Personal introduction"), help_text=_("maximum number of characters: 80 characters"), max_length=80, ) school = models.CharField( verbose_name=_("School name"), max_length=100, blank=True, null=True ) school_details = models.CharField( blank=True, null=True, verbose_name=_("School details"), help_text=_("example: Faculty of Medicine"), max_length=100, ) location = models.CharField( verbose_name=_("Location"), max_length=50, blank=True, null=True, help_text=_("example: Osaka"), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, verbose_name=_("User") ) I needed to create a modelform as I am rendering a customized template to set up profile after signing up: from django import forms from django.forms import ModelForm class ProfilePageDetailsForm(ModelForm): intro = forms.CharField( required=False, widget=forms.Textarea, label=_("Personal introduction"), help_text=_("maximum number of characters: 80 characters"), max_length=80, ) class Meta: model = ProfilePage fields = [ "avatar", "title", "school", "location", "intro", ] my view.py: def profile_details(request: HttpRequest, pk: int = None) -> HttpResponse: user = cast("User", request.user) profile = ProfilePage.objects.get(pk=pk) form = ProfilePageDetailsForm(instance=profile) if request.method == "POST": form = ProfilePageDetailsForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect("wagtailadmin_home") context = { "user": user, "form": form, } return render(request, "account/profile_details.html", context) … -
System check identified some issues:
ERRORS: <class 'shop.admin.ProductAdmin'>: (admin.E122) The value of 'list_editable[0]' refers to 'price', which is not contained in 'list_display'. <class 'shop.admin.ProductAdmin'>: (admin.E122) The value of 'list_editable[1]' refers to 'available', which is not contained in 'list_display'. System check identified 2 issues (0 silenced). -
Is there any method to join to querysets using django
I have two models defined something like class Temperature(models.Model): timestamp=models.DateTimeField() temperature=models.FloatField() class WaterLevel(models.Model): timestamp=models.DateTimeField() data=models.JSONField() I have a database function defined as class Bucket(models.Transform): template = "EXTRACT(EPOCH FROM %(expressions)s)::bigint/%(bucket_size)d" allow_distinct = True def __init__(self, expression, bucket_size=5,**extra): if bucket_size<0: raise ValueError('Bucket size must be a positive integer') super().__init__(expression, bucket_size=int(bucket_size), **extra) I then have a function that does something like def get_buckets(bucket_size): temperature_readings = ( Temperature.objects.values(bucket=Bucket("timestamp", bucket_size=15)) .annotate(temperatures=Count("timestamp")) .values("bucket", "temperatures") ) water_levels = ( WaterLevel.objects.values(bucket=Bucket("timestamp", bucket_size=15)) .annotate(levels=Count("timestamp")) .values("bucket", "levels") ) # This doesn't work, because there is no join method on a query_set return temperature_readings.join( water_levels, on=Q(tick=OuterRef("tick")) ).values_list("tick", "temperatures", "water_levels") Obviously the join method used doesn't exist and as such its signature is entirely constructed. I would expect this to return something like [ ( 1234, 10, 15), ( 1235, None, 15), ( 1236, 10, None), ( 1239, 1, 12), ... ] is there any method built into Django to accomplish this? -
request.POST not reading form data in django
I have my views file: from django.shortcuts import render from .models import Note # Create your views here. def index(request): return render(request, "index.html", {}) def write(request): notes = Note.objects return render(request, "write.html", {}) def create(request): if request.POST: body = request.POST['note'] title = request.POST['title'] print(f'title = { title }\nbody = { body }' and my html code: <h1>CREATE A NOTE</h1> <form action="{% url 'notes:create' %}" method="post"> {% csrf_token %} <label for="title">Title</label> <input type="text" name="title"><br> <label for="note">Note</label> <input type="text" name="note"><br> <input type="submit" value="Submit"> </form> Whenever I submit this form and try to access either the title or note values I get a MultiValueDictKeyError