Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Legend Picking using matplotlib (python file )
I created an API using django for plot visualisation I am connected to my database and i would like to add to my plot this animation of legend picking , but something wrong , someone can correcting me ? def one (df_a, a, b, c=2): X = df_a.iloc[:, a:b].to_numpy() l = X.shape[0] D = np.zeros((l, l)) idx = range(len(X)) for j in range(1, X.shape[0]): A = X D[j, idx] = np.abs(A).max(1) d = D.sum(0) / l diff = np.sort(d)[1:] - np.sort(d)[:-1] if np.where(diff > c * np.median(diff))[0].size != 0: t = np.sort(d)[np.where(diff > c * np.median(diff))[0] + 1].min() return df_a.iloc[np.where(d >= t)].index def two (df_a, a, b, c): outliers = one(df_a, a, b, c) colors = 'red' plt.figure(figsize=(20, 10)) plt.xlabel('pi ---> ') plt.ylabel('ab ---> ') plt.plot(df_a.to_numpy()[:, 1:].T, 'blue') for i, outlier in enumerate(outliers): plt.plot(df_abs.loc[outlier].iloc[1:], c=colors[i], label=outlier) plt.legend() legend = plt.legend() legend.set_picker(True) def on_pick(event): legline = event.artist origline = lined[legline] visible = not origline.get_visible() origline.set_visible(visible) legline.set_alpha(1.0 if visible else 0.2) fig.canvas.draw() fig.canvas.mpl_connect('pick_event', on_pick) plt.show() ``` -
Django many-to-many filtering gives "No operator matches the given name and argument types."
I have the following models in my Django project: model Profile(models.Model): user = models.OneToOneField(User) faculties = models.ManyToManyField('users.Faculty', related_name='profiles') Now I want to define a function that gives me all coworkers of a user/profile like so: def coworkers(self): coworkers = User.objects.none() for faculty in self.faculties.all(): coworkers |= User.objects.filter(Q(profile__faculties__id__exact=faculty.id)) return coworkers But then I always run in a ProgrammingError at /exercise/ operator does not exist: character varying = integer or No operator matches the given name and argument types. You might need to add explicit type casts. ) was the direct cause of the following exception:. I also tried: faculties = [f.id for f in self.faculties.all()] coworkers = User.objects.filter(Q(profile__faculties__id__in=faculties) Both versions also do not work with __exact instead of __in. Any help? -
CSS text trasform not taking affect to the data in database
I'm new to django and I've a problem that in my forms.py I've added "text-transform:capitalize" and it is working properly in the UI but when the data is saved the value becomes the old one. -
Error to run manage.py. I'm trying to run manage.py server but it hit some error! I've just trying to run a timetable generator
PS C:\Users\user\Desktop\TimetableGenerationSystem-master\projttgs> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Python310\lib\site-packages\django\core\management\base.py", line 546, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E009) Your URL pattern 'timetable_generation/render/pdf' [name='pdf'] has an invalid view, pass Pdf.as_view() instead of Pdf. WARNINGS: account.Profile: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the AccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.model s.BigAutoField'. ttgen.Department: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the TtgenConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models. BigAutoField'. ttgen.Instructor: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the TtgenConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models. BigAutoField'. ttgen.Room: (models.W042) Auto-created primary key used when not defining … -
RecursionError: maximum recursion depth exceeded (pythonanywhere)
I've deployed a DRF project on pythonanywhere. I have several endpoints like products, collections, carts and ... products and collection endpoints are ok. but it's not ok when I try to visit other endpoints like carts (all endpoints work in local) 2022-09-04 07:36:45,190: Error running WSGI application 2022-09-04 07:36:45,210: RecursionError: maximum recursion depth exceeded 2022-09-04 07:36:45,211: File "/home/piriecommerce/.virtualenvs/myenv/lib/python3.9/site- packages/django/core/handlers/wsgi.py", line 131, in __call__ 2022-09-04 07:36:45,211: response = self.get_response(request) -
DJango model logic
is it possible to have a logic based on the choices like: class model(models.Model): a = something(choices) b = foreingkey to c etc and then if a choices are yes show c ForeignKey table or just like that class model(models.Model): a = something(choices) b = something else etc if a choice is yes show b else only a -
html & django resize img-parent div to one size
In my application I let the user upload images. They are all displayed in a grid system. But because of there different aspect ratio it´s of course not possible that they have the same size. Are there any possibilities although the images aren´t the same size but let the parent-div be the same size for all projects. Thanks here is my template <div class="container"> <div class="row"> {% for project in projects %} <div class="col-lg-3 col-md-4 col-sm-6"> <div class="border border-dark"> <img class="card-img-top" src="{{project.featured_images.url}}" alt="Card image cap"> <h5 class="text-center">{{project.title}}</h5> </a> <ul class="list-group list-group-horizontal"> <li class="list-group-item flex-fill">{{project.price}} €</li> <li class="list-group-item flex-fill">{{project.location}}</li> </ul> </div> </div> {% endfor %} </div> </div> -
CSRF token from POST incorrect when running 2 Django containers in the same Docker host
I run two Django projects in a Docker host with Compose and both projects communicate with each other through a Docker network called mynetwork. Everything works fine, however, when I log in the admin section of project A and then open a new tab to log into the admin section of project B, then user from project A get disconnected with this message: CSRF verification failed. Request aborted. Reason given for failure: CSRF token from POST incorrect. And vice versa, when I log in the admin section of project B and load a tab with the admin section of project A, user of project B is disconnected. Both projects use custom AUTH_USER_MODEL. I tried to deactivate CsrfViewMiddleware middleware and play with the parameters below but I don't notice any change. How can I solve this issue ? settings.py Project A & B MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "corsheaders.middleware.CorsMiddleware", 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_structlog.middlewares.RequestMiddleware', 'django_structlog.middlewares.CeleryMiddleware', ] AUTH_USER_MODEL = 'authentication.User' # SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'http') # CSRF_USE_SESSIONS = True # CSRF_COOKIE_HTTPONLY = True docker-compose.yml Project A version: '3.8' services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: controller_django command: python manage.py runserver 0.0.0.0:8001 volumes: - .:/app expose: - 8001 ports: … -
AttributeError: 'NoneType' object has no attribute 'aptTime' in Django
I have an appointment model for patient to book appointment with a doctor, i used a custom user model for both doctor and patients, using is_staff and is_patient to differentiate them... class Appointment(models.Model): doctor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='staff', on_delete=models.SET_NULL, null=True) patient = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+', on_delete=models.SET_NULL, null=True) aptTime = models.DateTimeField(blank=True, null=True) pending_approval = models.BooleanField(default=True, null=True) approved = models.BooleanField(default=False, null=True) in my views.py i am trying to set the patient to request.user and doctor to the context i passed through the url, so i have the form_valid method to create appointment like this... class AppointmentCreateView(CreateView): model = Appointment fields = ['aptTime'] template_name = 'patients/Appointment-Createview.html' def form_valid(self, form, *args, **kwargs): form.instance.doctor = self.kwargs['pk'] #TODO change to doctor instance form.instance.aptTime = self.object.aptTime form.instance.patient = self.request.user form.save() i got an error saying ValueError: Cannot assign "1": "Appointment.doctor" must be a "User" instance. Internal Server Error: /patient/Appointment-Create/1/ After searching around SO i was able to change my code to... ...Some code... def form_valid(self, form, *args, **kwargs): User = get_user_model() doc = User.objects.get(id=self.kwargs['pk']) form.instance.doctor = doc #TODO change to doctor instance form.instance.aptTime = self.object.aptTime form.instance.patient = self.request.user form.save() now i'm getting a new error saying form.instance.aptTime = self.object.aptTime AttributeError: 'NoneType' object has no attribute 'aptTime' I am using … -
Is it better to interact query_set like Sets or use built-in functions?
I want to write a complex query that needs union and intersection. When I checked this QA, I found two approaches. So my need would be accomplished by needed_keys = [A, B, C] qs1 = model.objects.filter(entity=needed_keys[0]) for entity in needed_keys: qs1 = qs1 | model.objects.filter(entity=entity) qs2 = qs2 & qs1 or needed_keys = [A, B, C] qs1 = model.objects.filter(entity=needed_keys[0]) for entity in needed_keys: qs1 = qs1.union(model.objects.filter(entity=entity)) qs2 = qs2.intersection(qs1) based on one of the answers, I assume that the first approach would evaluate the result of the queries and then calculate the result of the AND or OR at the python level, Although I haven't seen anything about this evaluation in Django's doc. To sum up, my questions are, Which approach is better? Is Django really evaluates 'model.objects.filter(entity=entity)' each time in the loop of the first approach? P.S. please do not focus on the variable names or structure of the code, the goal was just to illustrate the situation. the type of 'entity' is textField, so I can't use 'model.objects.filter(entity__in=needed_keys)' when I checked the output of 'q2.query', the first approach was more readable for me but I want to be sure about its performance too. -
How can i give 2 domains to my Django project that contain 2 differen apps inside that is hosted on digital ocens app platform?
I have a Django project that is hosted on the Digital Oceans App Platform. My project contains 2 Django apps inside I want to give the main domain to 1 Django app and the subdomain to the other Django app. I'm using google domains. If someone kindly guides me how can I do this with the Digital Oceans App platform? -
break the loop when list len reaches to 5 (In for loop)
I am building a simple python program and I am trying to filter some response based on limit to run the for loop or while loop. What I am trying to do ? I am trying to stop the loop when list len reaches to 5. It can be a for loop and while loop. views.py def filter_array(request): new_array = [] count = 1 quit = False for m in res.get("blogs"): for likes in m.get("likes"): try: count += 1 if likes == "user_1": new_array.append(likes) if count == 5: quit = True break except: quit = True break print(new_array) return new_array json response in views.py res = { "blogs": [ { "title": "Blog 1", "description": "Blog description", "likes": [ "user_1", "user_2", ] }, { "title": "Blog 2", "description": "Blog description", "likes": [ "user_4", "user_5", ] }, { "title": "Blog 3", "description": "Blog description", "likes": [ "user_3", ] }, { "title": "Blog 4", "description": "Blog description", "likes": [ "user_3", "user_4", "user_5", ] }, { "title": "Blog 5", "description": "Blog description", "likes": [ "user_4", "user_5", ] }, ] } When I run the above code then It is appending all the json items in the array. But I want to append in list … -
how can I use multiple {% block content %} inside base template in django?
So, I have this base html where for example I am using it like this <html> <body> <nav> navbar </nav> <div class= "content"> {% block content %} {% endblock %} </div> ............. My question is can I use multiple block contents in the same base html ? So that I can extend the parent and add elements in whatever block I want ? like this - <html> <body> <nav> navbar </nav> <div class= "content"> {% block content %} {% endblock %} </div> <div class = "summaries"> {% block content %} {% endblock %} </div> ............. Question might sound rookie. I am new to Django! -
'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte django
so i have variable contains with bytes and i want to write it to text and download it. but to use write, it's must in bytes. so how to make from bytes to string? now i got error like this. i tried to decode it, but it cannot works. 'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte here's the code: def create_file(f): print(f) #f = b'\x8b\x86pJ' response = HttpResponse(content_type="text/plain") response['Content-Disposition'] = 'attachment; filename=file.txt' filename = f print(filename) # filename = b'\x8b\x86pJ' download = filename.decode('utf-8') response.write(download) print(response) return response -
Python Django - unsupported operand type(s) for -: 'float' and 'NoneType'
I'm a beginner to python and Django, I tried to do searching but I can't find my answer to this. Can anybody help me with this please. code from my html: <td class="px-2 py-1 align-middle text-center"> {{ schedule.count_available|floatformat:0|intcomma }} </td> my model: class Schedule(models.Model): code = models.CharField(max_length=100) vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE) depart = models.ForeignKey(Location,on_delete=models.CASCADE, related_name='depart_location') destination = models.ForeignKey(Location,on_delete=models.CASCADE, related_name='destination') schedule= models.DateTimeField() fare= models.FloatField() status = models.CharField(max_length=2, choices=(('1','Active'),('2','Cancelled')), default=1) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.code + ' - ' + self.vessel.vessel_number) def count_available(self): booked = Booking.objects.filter(schedule=self).aggregate(Sum('seats'))['seats__sum'] return self.vessel.seats - booked error: error image -
Mixins cause a blow up when migrating
Mixins: class ExamPartMixin(models.Model): exam_part = models.ForeignKey('exam_parts.ExamPart', null=True, on_delete=models.CASCADE, ) class NameMixin(models.Model): name = models.CharField(max_length=255, null=False, default="") def __str__(self): return self.name class Meta: abstract = True Model: class ExamSection(NameMixin, ExamPartMixin, CommentMixin): class Meta: constraints = [ models.UniqueConstraint( fields=['exam_part', 'name'], name='part_section') ] Problem wnem migrating exam_sections.ExamSection: (models.E016) 'constraints' refers to field 'exam_part' which is not local to model 'ExamSection'. HINT: This issue may be caused by multi-table inheritance. task_descriptions.TaskDescription: (models.E016) 'constraints' refers to field 'exam_part' which is not local to model 'TaskDescription'. HINT: This issue may be caused by multi-table inheritance. Could you help me? Should I refrain from using mixins here? I like mixins and would like to use them. -
I have code changes which change the future object field, should i make changes in code to change all the old one or should i do it in db
Object is stream { uuid: '32digituuid', virtual_path=path } now according to new change the virtual will be changed for all new stream objects, but i need changes in old one too.Should i make changes in code to make those changes or do it separately in db. -
Deploy django + mysql + celery + redis in aws
I'm new in aws and I would like to ask how to deploy django with mysql, redis and celery in aws? -
No module named 'admin_ordering' even after pip install admin_ordering in venv and it shows in /venv/lib/
ok my settings INSTALLED_APPS looks like this INSTALLED_APPS = [ 'correlator.apps.CorrelatorConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'admin_ordering', ] After installing with pip with venv activated pip intall admin_ordering I see in venv/admin_ordering in my models.py import datetime from flag.models import Flag from django.db import models from django.utils import timezone from django.contrib.contenttypes.fields import GenericRelation from django.utils.translation import gettext_lazy as _ what step am I missing? -
How to take multiple inputs from the same input field and display each value individually?
I have input field like this : <form action="worldle" method="post"> {% csrf_token %} <input type="text" name="text" placeholder="Guess the Flag"><br> <input type="submit" name="Submit"> I want to display each value in the list. For that i've created a list like this : <div class="card" style="width: 18rem;"> <ul class="list-group list-group-flush"> <li class="list-group-item">{{ values }}</li> <li class="list-group-item">{{ values }}</li> <li class="list-group-item">{{ values }}</li> </ul> </div> I don't know how to display second value and third value in the second and third list . views.py is : def worldle(request): value= request.POST.get('text',False) values = value.lower() world= Worldle.objects.all() rand=random.choice(world) bcd= rand.title.lower() result = '' if values == bcd: messages.info(request, 'Correct') result = 'correct' else: result='Wrong' return render(request,'worldle.html',{'rand':rand,'values':values,'rst':result}) So I want to display multiple values in the list from the same input field. How do I achieve this? Thanks -
Fixing a NoReverseMatch Error for a Django Project
I am trying to fix a No Reverse Match error for my django project but I am unable to figure out the reason and the sequence of thinking to fix it. My objective is to click on a button and change the status of a boolean from False to True and if the status is False to appear and if it is true disappear. Here is the model: class Workout(models.Model): active = models.BooleanField(default=False) Here is the view: def change_status(request, pk): url = request.META.get('HTTP_REFERER') # get last url startsession = Workout.objects.get(id=pk) startsession.active = True startsession.save() return HttpResponseRedirect(url) Here is the template: {% if startsession.active %} <button disabled="disabled" type="button">Start the workout</button> {% else %} <a href="{% url 'my_gym:bla' startsession.pk %}"> <--------Error here <button type="button">Start the workout</button> </a> {% endif %} here is the url: path('workout/bla/<int:pk>/', change_status, name='bla'), and finally here is the error Traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File … -
Is it possible to include djoser urls and custom model urls in one querystring?
urlpatterns = [ path('users/', include('users.urls')), path('users/', include('djoser.urls')), path('users/', include('djoser.urls.jwt')), ] it gives me error when I try to include djoser.urls and users.urls in one path. Are there any options to do this? -
Can't set user.is_active and user.is_superuser to True
I need to use email for authentication instead of user but when ever I create super user it doesn't set the is_active and is_superuser to True which are False by default! models.py class CustomUserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('User must have an email') if not password: raise ValueError("User must have a password") user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user(email, username, password) user.is_active = True user.is_staff = True user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField(max_length=200,unique=True) username = models.CharField(max_length=200, unique=True) last_login = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email objects = CustomUserManager setting AUTH_USER_MODEL = "account.User" SQL table for users id ... is_active is_staff is_admin is_superuser 1 ... 0 1 0 1 2 ... 0 1 0 1 3 ... 0 1 0 1 4 ... 0 1 0 1 -
Zero Values Not Shown in Integer Field of Django Form
In a Django project, I have a very simple form with three integer fields: class SpecItemForm(forms.Form): n1 = forms.IntegerField() n2 = forms.IntegerField() n3 = forms.IntegerField() def __init__(self, *args, **kwargs): super(SpecItemForm, self).__init__(*args, **kwargs) I instantiate the form from views.py with code like this: initial_values = {} initial_values['n1'] = 1 initial_values['n2'] = 0 initial_values['n3'] = 3 form = SpecItemForm(initial=initial_values) I expect the form to be rendered with the specified initial values for the three integer fields but this only works for non-zero initial values. For instance, in the example above, I see the initial values for fields n1 and n3 (initial values are, respectively, '1' and '3') but not for n2. Why is an initial value of zero not rendered? -
How to convert an array of objects to object of objects in python
How do I convert this array of objects to object of objects in python [ { "id": 7, "name": "science" }, { "id": 8, "name": "Sports" }, { "id": 9, "name": "culture" }, { "id": 10, "name": "Communication" } ] I will like it to be like this { { "id": 7, "name": "science" }, { "id": 8, "name": "sports" }, { "id": 9, "name": "culture" }, { "id": 10, "name": "Communication" } }