Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
slicing any filed of Django form
Is it possible to slice two field for adding hr HTML tag after fields? forms.py class FactureForm(forms.Form): Facture_No = forms.CharField(label='Facture Number', required=False) Beställare = forms.CharField(required=False) Actually I want to add hr tag between Facture_No and Beställare -
Use original image size and aspect ratio in the carousel component in Django CMS
I am using the carousel component for Django CMS from the front-end plugins. I have a problem with the image size and aspect ratio. I tried an approach to manage the CSS file according to this source: Maintain image aspect ratio in carousel However, this is not solving my problem. The image is still being cropped and downsampled, resulting in low resolution. I want to display the images in full view and in their original aspect ratio. However, the carousel component from the plugin only allows the use of fixed aspect ratios, which do not correspond to my image aspect ratio. I didn’t find the possibility to use or select the image’s original aspect ratio. Moreover, it seems that the carousel component loads a downsampled and cropped version of the image. If I understood correctly, the image loading response is from the thumbnail component: djangocms_frontend/contrib/carousel/templates/djangocms_frontend/bootstrap5/carousel/default/image.html {% load cms_tags easy_thumbnails_tags %} {% if instance.rel_image %} {% thumbnail instance.rel_image options.size crop=options.crop upscale=options.upscale subject_location=instance.rel_image.subject_location as thumbnail %} <img class="d-block w-100" src="{{ thumbnail.url }}" alt="{{ instance.rel_image.default_alt_text|default:'' }}" /> {% else %} <div class="d-block w-100" style="aspect-ratio: {{ aspect_ratio }}"> {% for plugin in instance.child_plugin_instances %} {% render_plugin plugin %} {% endfor %} </div> {% endif … -
Django and Celery old data persistency issue
I am having an issue with my django application using celery workers. I have a task that takes 2 input variables then passes them to an external function to perform a webscraping operation on them. The issue is that even though in the logs model I created it registers the correct new user_id and swimmer_id each time the task is executed it seems to get the swims information from the very first time the task was executed as opposed to the current execution. When the worker is restarted the issue resolves until you try to perform a second execution again. In my code below I can show you the setup I am using, @shared_task(bind=True) def process_swimcloud_merge(self, id, user): print(id) user = User.objects.get(id=user) print(user.first_name) swims = extract_recent_swims(user.id, id) #More swim processing code here, irrelevant to query return def extract_recent_swims(user_id, swimmer_id): meet = find_all_meets(swimmer_id)[0] a_tag = meet.find('a', class_='c-swimmer-meets__link-mask') link = a_tag.get('href') swims = extract_swims(link) swim = swims[-1] UserActionLogs.objects.create( user = User.objects.get(id=user_id), accessing = f'UID: {user_id}, SID {swimmer_id}, Swim: {swim.title}, {swim.time}') return The problem here is that in the UserActionLogs, it correctly logs whatever the user_id and swimmer_id are on each execution however it logs whatever the original swim was from the first … -
Static files not served while deploying Django application with Lighttpd and Gunicorn
I am working on my first Django project. I want to host the same using Lighttpd server rather than nginx or apache. The project works well in the developer mode. The 'runserver' serves all the files as intended. Since Lighttpd alone cannot host a Django project, I use Gunicorn to serve the dynamic aspects. Django version - 3.2 Gunicorn - 21.2 Python - 3.8 Lighttpd - 1.4.52 I have configured my Lighttpd in a separate conf file named myapp.conf without amending the default lighttpd.conf file. When I run the server, I see that Gunicorn loads index.html correctly but css files are not loaded by lighttpd. It gives the following error: GET https://ip-address/myapp/static/css/indexStyle.css net::ERR_ABORTED 404 (Not Found) Similarly Gunicorn gives an error when loading js file: GET https://ip-address/myapp/static/js/TM_PageFun.js net::ERR_ABORTED 404 (Not Found) Refused to execute script from 'https://ip-address/myapp/static/js/TM_PageFun.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I find a lot of information here on connecting Django with Nginx and Gunicorn. But I couldn't find much with Lighttpd. I am not sure where the error is. I have added the mime-types and double checked the path and permissions. CSS files are in /usr/web/myapp/static/css JS files … -
Django ForeignKey("x") field must be a "x" instance on update
Django version 4.2.9 I try to fix this : Cannot assign "('customer',)": "Project.customer" must be a "Customer" instance. I have 2 classes, Project and Customer. class Customer(models.Model): customer_name = models.CharField(max_length=50) string = models.CharField(max_length=50) def __str__(self): return f"{self.customer_name}" class Project(models.Model): project_name = models.TextField() project_code = models.CharField(max_length=50,null=True,blank=True) project_scope = models.CharField(max_length=200,blank=True,null=True) customer = models.ForeignKey("Customer", on_delete=models.DO_NOTHING) project_type = models.ForeignKey("ProjectType", on_delete=models.DO_NOTHING) is_rd = models.BooleanField(null=True,blank=True) #TARIHLER request_date = models.DateField(auto_now=False, auto_now_add=False) confirmation_date = models.DateField(auto_now=False, auto_now_add=False, null=True,blank=True) estimated_finish_date = models.DateField(auto_now=False, auto_now_add=False) project_finish_date = models.DateField(auto_now=False, auto_now_add=False, null=True,blank=True,default="01/01/1970") update_date = models.DateField(auto_now=False, auto_now_add=False,null=True, blank=True,default="01/01/1970") start_date = models.DateField(auto_now=False, auto_now_add=False,null=True, blank=True,default="01/01/1970") #TARIHLER update_count = models.IntegerField(null=True,blank=True) estimated_cost = models.IntegerField() actual_cost = models.IntegerField(null=True,blank=True) is_active = models.BooleanField(default=False) project_leader_id = models.ForeignKey("account.MamurUser", on_delete=models.DO_NOTHING) bill = models.BooleanField() patent = models.BooleanField(default=False,blank=True) market = models.BooleanField(default=False,blank=True) is_confirmed = models.BooleanField(default=False,blank=True) is_pmo_confirmed = models.BooleanField(default=False,blank=True) This is my views.py: def edit_project(request): context={ "projects" : Project.objects.filter(is_confirmed=False) } if request.method == "GET": return render(request,'pyka/project-edit.html',context) else: post = request.POST project_id = post['project_id'] project = Project.objects.get(id=project_id) update_count = project.update_count update_count += 1 valid = True # değişecek error = None now = datetime.date.today() project_name = post['project-name'] customer = Customer.objects.get(id=post['customer']) type = ProjectType.objects.get(id=post['type']) project_scope = post['project-scope'] project_budget = post['project-budget'] user_data = post['userData'] user_data = json.loads(user_data) start_date = post['start-date'] end_date = post['end-date'] patent = post.get('patent', False) market = post.get('market', False) # … -
Bt table filter extension:- how to filter dropdown value filter out?
How to filter dropdown value based on new data on first filter. Like only $0 needned in second dropdown value Simple table value filter then based on filtered result value dropdown value come to UI. Thanks I see the github code for bt table filter extension but i didn't identify any idea -
Mypy: properly typing a Django mixin class when accessing a method on super()
Django has a quirk where it doesn't validate models by default before writing to the database. A non-ideal situation that devs try to work around by creating a Mixin class for example: https://www.xormedia.com/django-model-validation-on-save/ The idea of that workaround is that you can inherit this mixin to your custom defined Django models whenever you want to add validation-on-save to it. That approach works, but I'm trying to upgrade those old examples to a properly typed example. Below is my current code: from typing import Any, TypeVar from django.db import models DjangoModel = TypeVar('DjangoModel', bound=models.Model) class ValidateModelMixin: """Use this mixing to make model.save() call model.full_clean() Django's model.save() doesn't call full_clean() by default. More info: * "Why doesn't django's model.save() call full clean?" http://stackoverflow.com/questions/4441539/ * "Model docs imply that ModelForm will call Model.full_clean(), but it won't." https://code.djangoproject.com/ticket/13100 """ def save( self: DjangoModel, force_insert:bool=False, force_update:bool=False, *args: bool | str | None, **kwargs: bool | str | None, ) -> None: """Override the save method to call full_clean before saving the model. Takes into account the force_insert and force_update flags, as they are passed to the save method when trying to skip the validation. Also passes on any positional and keyword arguments that were passed … -
prefill previous file field data in django form
i have two file fields in django form and i want set prefill data for fields. when form open again dont need fill again file field. this is my form field self.fields['total_trial_balance'].widget.attrs.update({'class': 'filestyle', 'id': 'total_trial_balance'}) self.fields['Certain_trial_balance'].widget.attrs.update({'class': 'filestyle', 'id': 'Certain_trial_balance'}) this is i try to do form = TaxReturnLegalUpdateForm(instance=tax_return, request=request) but i just got currently file name in my templateenter image description here -
Why Hosted Site showing blank page in azure-django hosting?
I am trying to deploy my django app using azure(app services) through vs code. It is Showing deployment successful but hosted site showing blank page. I used VS Code. Downloaded azure studio extension and deployed my django project. -
Is this the right way of creating Multi User Access for Django?
I actually confused right now on how to implement the Multi-User Access with Django v5.3. I am actually new in this backend and I would like to create a login where users can redirect to specific dashboards based on their accesslevel type (Providers,Admin,Validator,Students). Here is the app that I made so far... I have no views yet because I am not confident enough to my models.py but I hope this is good enough. from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_student = models.BooleanField(default=False) is_validator = models.BooleanField(default=False) is_provider = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.FileField address = models.CharField(max_length=50) gwa = models.FloatField(max_length=100) graduated_at = models.CharField(max_length=100) year = models.DateField() class Validators(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.FileField address = models.CharField(max_length=50) class Provider(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_address = models.CharField(max_length=100) phone_no = models.CharField(max_length=11) company_website = models.CharField(max_length=100) avatar = models.FileField class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.FileField(upload_to='avatars') -
how to use multiple model in single serializer or how to make combined serializer but not extended approch
i'm implementing API in which i have to store data in multiple database table and i can not change the schema , so here i have implement the serializers by multiple inharite approch. here is my serializers: class Organization_1_Serializer(serializers.ModelSerializer): def __init__(self, instance=None, data=..., **kwargs): super(Organization_1_Serializer, self).__init__(instance, data, **kwargs) class Meta: model = Organizations fields = "__all__" class Organization_2_Serializer(serializers.ModelSerializer): def __init__(self, instance=None, data=..., **kwargs): super(Organization_2_Serializer, self).__init__(instance, data, **kwargs) class Meta: model = Organization_2 fields = "__all__" class OrganizationSerializer(Organization_1_Serializer, Organization_2_Serializer): def __init__(self, instance=None, data=..., **kwargs): super(OrganizationSerializer, self).__init__(instance, data, **kwargs) def create(self, validated_data): return super().create(validated_data) def update(self, instance, validated_data): return super().update(instance, validated_data) i want to create POST api in which i can simple pass the resquest.data to the OrganizationSerializer and serializer will manage the things according to the model. my concern to use ModelSerializer instead Serializer that single api contain 3-4 tables fields and each table has the appox 20-25 columns to manage. using serializers.Serializer or accept ModelSerializer it's becoming so complex. please help me to solve this issue aur suggest right approch to do so. Thank you in advanced -
Django The current path didn’t match any of these
Good day, I have made a simple calculator in Django displaying on the url path('', vieuws.home, name='home'), It uses a function from the views.py file to render the answer and then display it using the result.html file. This works perfect. But I want to make more calculators on different urls and then it does not work anymore. I put the same calculator on the path('count/', views.count, name='count'),. I renders the page good but to pass in the result.html page for the answer does not work and gives a 404 error, something wrong with the url path. I have tried to change order in the urls and change order in the views.py file but I can not figure out how to solve the problem. I hope it's okay to add the link of the project to see the code on github, https://github.com/Roelofplanet/Django-calculator Thanks! Regards, Roel -
Download load button on django project not working with apache server
I am having problems with my download button on my website which should allow vistors to get a copy of my CV. It was working while through all the stages of building the site, however when running it with apache2 a blank tab just opens up. This is the layout of the project: enter image description here the html code: enter image description here the views.py: enter image description here my dango_project.config on server: enter image description here and the error log I get when I click the button: enter image description here I am new to configuring an apache server so I am guessing its somthing to do with my .config file? Any help or pointing in the right direction would be much appreciated Thank you I am just expecting the user to be able to download a copy of my CV. Was working when running manage.py server on local host and linux server. Every other part of the site works, like sending forms uploading images/text. -
OperationalError at /admin/useraccounts/student/ :no such column: useraccounts_student.user_id
I am trying to connect my User table to these three user access from models. But when I view the models in django admin it gives me an error unless the OnetoOnefield is removed. I am just a beginner to this python framework so please bear with me. I can view the other models except for the 3 user models for this app. This is what the models looked liked (I don't have view.py yet because I am still figuring out if the models worked fine) models.py ` from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_student = models.BooleanField(default=False) is_validator = models.BooleanField(default=False) is_provider = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) class Meta: db_table = 'useraccounts_user' class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ##Added this avatar = models.FileField address = models.CharField(max_length=50) gwa = models.FloatField(max_length=100) graduated_at = models.CharField(max_length=100) year = models.DateField() class Validators(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE)##Added this avatar = models.FileField address = models.CharField(max_length=50) class Provider(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE)##Added this company_address = models.CharField(max_length=100) phone_no = models.CharField(max_length=11) company_website = models.CharField(max_length=100) avatar = models.FileField class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE)##Added this avatar = models.FileField(upload_to='avatars') ` -
Logout Across Tabs in django [closed]
I need user will logout automatically in all tabs when logged out in one open tab of browser without page refresh. How can I implement this in django ? -
Not redirecting to desired URL on Django even after the configuration
This is my django project. I added my APP's url in project.urls. I also added my app's name in INSTALLED_APPS but yet all I see is only admin/ page. practise.urls hello.urls even after entering right url, it dont recognize, the list only says /admin I searched but couldn't find solution. All the urls that I am adding in urlpatterns are not being recognized except for admin. -
How can I implement an audio CAPTCHA reader with django-simple-captcha in Django?
I'm looking to enhance the accessibility of my Django web application by integrating an audio CAPTCHA reader alongside the text-based CAPTCHA provided by django-simple-captcha. While the text-based CAPTCHA is effective for most users, some users may have difficulty reading the text due to visual impairments or other reasons. I've read the documentation, but I can't understand how to implement... https://django-simple-captcha.readthedocs.io/en/latest/advanced.html#captcha-sox-path -
Not sure why when I press signup it just returns to the blank form, and when i try to log in it does nothing
views urls trying to create a new user with the sign up page, but it just returns a blank form. i created a superuser and am able to login in that and it works fine but cant figure out the problem with the signup page... -
Is there a signal available in Djoser specifically?
Is there a signal available in Djoser specificall or would I need to create a custom signal to handle actions upon a user's first registration using Google login? The user_registered of(djoser) signal doesn't seem to be functioning when registering with Google login. https://djoser.readthedocs.io/en/latest/signals.html thanks -
Transition to Backend Engineer roles [closed]
I am currently a Site Reliability Engineer, but I am interested in transitioning to more backend-focused roles that involve coding. Could you provide some advice on how to prepare for these positions and where to begin? I started with learning FastApi and Django since I know python. I also know a bit of golang. -
How can I display the DateTimeField in the django template as it's display in the admin when I create a view?
This is my model: class Event(models.Model): title = models.CharField(max_length = 255) club = models.CharField(max_length=70) event_image = models.ImageField(upload_to="event_images", default='aqsa_copy.jpeg', blank=True) date = models.DateTimeField(null = True) location = models.CharField(max_length=30) first_name = models.CharField(max_length=15) This is how it displayed in the admin: I want to make it like this at the template, and be able to pick a date and time. But what I got for now is that: Please help me if you can? -
how to implement render in view controller after get request Django
I have the following template in which I added a get request function openProject(projectId) { fetch(`/segmentation/test/`, { method: 'GET', headers: { 'Content-Type': 'application/json' }, mode: 'same-origin', }) .then(response => { if (response.ok) { console.log("Всё супер"); } else { console.error('Ошибка при открытии проекта'); } }) .catch(error => { console.error('Произошла ошибка:', error); }); } and the next view in it I collect all the information about images and tags that relate to this project def test(request): projectId = request.GET.get('projectId') if projectId: project = Project.objects.get(pk=projectId) _tags = project.tags.all() _images = project.images.all() print(_images) polygons = [] colorPol = [] for i in range(len(_images)): polygons.append([]) colorPol.append([]) for i in range(len(_images)): for rect in Rect.objects.all().filter(inImage=i+1): tempArr = [] colorPol[i].append(rect.tag.Name) for p in rect.points.all(): tempArr.append([p.x, p.y]) polygons[i].append(tempArr) else: _tags = [] _images = [] polygons = [] colorPol = [] return render(request, 'segmentation/testDraw.html', {'tags': _tags, 'images': _images, 'title': 'Test Draw', 'rectForImage': polygons, 'colorPolArr': colorPol}) My urls: app_name = 'segmentation' urlpatterns = [ path('test/', test, name='testDraw'), path('projects/', project_show, name='project_show'), ] please help me solve this problem I tried changing the request to post, but as far as I understand it doesn’t matter -
Django Automatic Field Creation
Is there a way to automatically generate a new field when a model that is foreignkeyed is created class Metric(models.Model): name = CharField(null = True, blank = True, max_length = 200) abbreviation = CharField(null = True, blank = True, max_length = 10) def __str__(self): try: return self.name except Exception as e: return str(e) class Test(models.Model): name = CharField(null = True, blank = True, max_length = 200) metrics = ManyToManyField(Metric, null = True, blank = True) def __str__(self): try: return self.name except Exception as e: return str(e) class TestVariable(models.Model): independent_variable = ForeignKey(Variable, null = True, blank = True,on_delete = models.CASCADE, related_name = "independent_variables") dependent_variable = ForeignKey(Variable, null = True, blank = True, on_delete = models.CASCADE, related_name = "dependent_variables") test = ForeignKey(Test, null = True, blank = True, on_delete = models.CASCADE) def __str__(self): try: return self.name except Exception as e: return str(e) So if I created a new Metric, is there a way to automatically add a field to TestVariable for example, if I created a Metric for standard deviation, it would automatically create a field in TestVariable to take a numerical value of the standard deviation. -
Datetime format for forms and databases
I am having difficulty unifying the format for all the dates, in my database, the format is year month day, and in my form is year month day min second. I want the date format to be unified but i seem to cant do it. def get_unavailable_dates(request, car_id): try: busy_dates = BusyDate.objects.filter(car_id=car_id) unavailable_dates_list = [busy_date.start_date.strftime('%Y-%m-%d') for busy_date in busy_dates] except BusyDate.DoesNotExist: unavailable_dates_list = [] busy_dates_json = [{'title': 'Busy', 'start': busy.start_date, 'end': busy.end_date} for busy in busy_dates] return JsonResponse(busy_dates_json, safe=False) def save_busy_dates(request): if request.method == 'POST': car_id = request.POST.get('car_id') busy_dates = request.POST.getlist('busy_dates[]') # Assuming busy_dates is sent as a list # Iterate over busy_dates list and create BusyDate instances for date_str in busy_dates: busy_date = BusyDate(car_id=car_id, start_date=date_str.date(), end_date=date_str.date()) busy_date.save() # Save the instance to the database return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)``` I tried to add .date() where possible -
Incognito/Private Browsing Not Working for Google OAuth2 Authorization URL
When I navigate to http://127.0.0.1:8000/auth/o/google-oauth2/?redirect_uri=http://127.0.0.1:4200/google, I receive the following response "authorization_url": "https://accounts.google.com/o/oauth2/auth?client_id=xxxxxxxx&redirect_uri=http://127.0.0.1:4200/google&state=xxxxxxx&response_type=code&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+openid+openid+email+profile" However, when I attempt to open this URL(authorization_url) in an incognito/private browsing window, it does not work. i have set CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True and "SOCIAL_AUTH_ALLOWED_REDIRECT_URIS": ["http://127.0.0.1:4200/google"], i have [23/Apr/2024 22:07:31] "POST /auth/o/google-oauth2/ HTTP/1.1" 400 53