Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unicode slug dose not work after deploying in iis8
i need help to solve my problem, i deployed a django web app in iis 8 that contains Persian slug, in development everything ok but when i deployed the app in iis 8, the app urls that contains Persian Unicode characters are not working. this is my url.py from . import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include, register_converter from .views import * from django.urls.converters import SlugConverter class CustomSlugConverter(SlugConverter): regex = '[-\w]+' register_converter(CustomSlugConverter, 'custom_slug') urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include('tour.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('', IndexPage, name='index-page'), path('tour/<int:id>/custom_slug:Slug>', TourDetail, name='tour-detail'), path('hotels/<int:id>/<custom_slug:Slug>', HotelDetail, name='hotel-detail') ] in my models.py Slug = models.SlugField(max_length=200, unique=True, null=False, verbose_name='لینک سئو') all URLs with English slug work but only Unicode slug dose not work in deployment, in development everything okay. thanks for your attention and replies -
UTF8 charset is not working in Django project
In my Django project, Russian Cyrillic symbols stopped working. For example, if I set some Cyrillic symbols to one variable and print it, string = "ввв" print(string) it is giving an error: UnicodeEncodeError: 'charmap' codec can't encode characters in position 1-3: character maps to <undefined> I tried this expression in my different Django project, and in that project, it is working well without any errors. -
Suggestions on improving a form view
I'm building an app where the user enters data and then gets redirected to a page that shows results based on their input with some simple equations. However, every time I refresh the results page, a new model instance is saved on the database. Is there another (more efficient and effective) way of passing the data from this view to another view where I have access to the instance of that model submitted through the form view? What's the Django way of passing form data to a view? The only limitation is I don't want user authentication so using self.request.user is not an option unless it can be implemented in a way that doesn't require users to sign up and sign in. I'm still somewhat new to Django so any pointers to obvious solutions that I'm overlooking would be greatly appreciated. This is the view that processes the model form: def createcalculation(request): form = CalcForm() if request.method == 'POST': form = CalcForm(request.POST) if form.is_valid(): item = form.save() m_data = get_object_or_404(Calculate, id=item.id) context = {'c_data': form.cleaned_data, 'm_data': m_data} return render(request, 'calc/res_ca.html', context) context = {'c_form': form} return render(request, 'calc/calc.html', context) -
django - AttributeError: 'function' object has no attribute 'as_view'
i'm a newbie and i can't fix this: def UserList(ListView): model = User template_name = 'core/users.html' path('users/', views.UserList.as_view(), name="user_list"), AttributeError: 'function' object has no attribute 'as_view' -
search for django-objects tagged with all tags in a set
In my django-project have a search function where you can specify tags, like "apple, banana" and by that query for objects of a certain model, tagged with taggit. When I do: tag_set = Tag.objects.filter(Q(name__in=tag_list)) query_set = Model.objects.filter(Q(tags__in=tag_set)) this gives me objects tagged with either "apple" OR "banana". But I want the AND operator... I tried: query_set = Model.objects.filter(reduce(operator.and_, (Q(tags__in=x) for x in tag_set))) but then I get 'Tag' object is not iterable. Any help? -
How to have an optional character field in a django form, but validate it so that an empty string is not allowed?
I have a form for a PATCH request similar to the following: class SampleForm(Form): optional_field = CharField(required=False, validator=[optional_text_field_validator]) This is the validator- def optional_text_field_validator(text): if len(text) == 0: raise ValidationError("This field cannot be empty") I have also tried- def optional_text_field_validator(text): if text == 0: raise ValidationError("This field cannot be empty") I am doing this so that it is not mandatory to include the optional_field in a request, but when it is present, it's value cannot be an empty string. However, the form validation is passing with both the above approaches (is_valid returns True), when it should be failing. How do I implement this? -
Schedule automated jobs in Django
Anyone knows how to schedule a Django script to run at a certain date and time? Example: User enters someone’s contact info on frontend, Django backend receives the form data, but doesn’t send the contact an email until 48 hours later. Anyone has an idea? I saw Cron, but looks like Cron needs to be executed and doesn’t automatically execute on its own? Just need help learning the scheduling feature. -
Why does my js function only run if called in the file and not on a onload?
It has been a while since I havent used JS and when I try to get my function to run onload nothing happens it should just print numbers to the console. It works if I call the function in the js file but not if I am trying to do a onload and pass parameters do I have to call the function in the file or can I call it in the html doc only? I am using Django if this affects anything. HTML <canvas id="homepage-stockGraph" style="background-color: white;" onload="test(1, 2, 3, 4)"></canvas> then I call this at the bottom of the page <script src="{% static 'js/canvas.js' %}"></script> Here is all of the js function test(x1, y1, x2, y2) { console.log('x1: ' + x1, + ', y1: ' + y1 + ', x2: ' + x2 + ', y2: ' + y2 ); } -
Nested subquery in django ORM
I need to transform this query to django, but I can't figure out how. SELECT SUM(income) FROM ( SELECT COUNT(keyword)* CASE WHEN country='ca' THEN 390 WHEN country='fi' THEN 290 WHEN country='it' THEN 280 WHEN country='nl' THEN 260 ELSE 250 END AS income FROM analytics_conversions WHERE keyword = 'online' AND click_time BETWEEN '2022-06-01' AND '2022-06-30' GROUP BY country) as _ Now I have this code, but it returns multiple rows. These rows should be summed and return only that one row to be used in a subquery. keywords_conversions_params = { 'keyword': OuterRef('keyword'), 'keyword_type': OuterRef('keyword_type') } keywords_conversions_value = Conversions.objects.filter( **keywords_conversions_params).order_by().values('keyword').annotate( value=Count('pk') * Case( When(country='ca', then=350), When(country='fi', then=290), When(country='it', then=280), When(country='nl', then=260), default=250 )).values('value') -
How can I generate a random unique User id value in django user model and show it on django admin?
I have a Model in django. I just extended the AbstractBaseUser and added some custom fields in the with BaseUserManager. Now I need to generate a unique Id as primary key and need to show it on django admin..How can I do that? my model is given below. from django.db import models from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, mobile, **extra_fields): if not email: raise ValueError("Email must be provided") if not password: raise ValueError('Password is not provided') user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, mobile = mobile, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',False) return self._create_user(email, password, first_name, last_name, mobile, password, **extra_fields) def create_superuser(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',True) return self._create_user(email, password, first_name, last_name, mobile, **extra_fields) class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=255) mobile = models.CharField(max_length=50) address = models.CharField( max_length=250) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name','mobile'] class Meta: verbose_name = 'User' verbose_name_plural = 'Users' -
How can I change django login form from username to email when users wanted to login
Is there anyways I can change django custom user login from Username to Email? I have try using this method but it does not work: def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(request, email=email, password=password) if user is not None: auth.login(request, user) return redirect('Home') else: messages.info(request, 'Invalid Credential') return redirect('login') else: return render(request, 'login.html') I want to allow user to login using Email not Username. -
Django Migrations in CI/CD pipeline
My CI/CD pipeline is triggered whenever there is a code push. There is an already populated database(PostgreSQL). I am doing changes in models.py (specifically adding a new model) and python manage.py makemigrations <app-name> and python manage.py migrate commands are written in docker entry-point file, so I expect that on every code push, these commands will execute and create migrations file and database should reflect changes. But database isn't showing any changes at all, however, Django's admin page is showing the new model name. Also, there is no migrations folder present in the repository at all in any app. How do i resolve it. I wanna add a new table and add a new column in an existing table -
How to restrict field options in Django Forms
I created a form that adds a permission to a user. However if a user has a permission already assigned it results in a UNIQUE KEY ERROR. How do I modify the form so that I don't display any users that already have permission assigned. In other words how do I restrict the field values/options of a form ? -
Django, how do I populate a bespoke form widget
I have created a bespoke form widget which saves an address as a list. class AddressWidget(MultiWidget): def __init__(self, base_widget, attrs=None): widgets = ( forms.TextInput(attrs={'placeholder': 'Address', 'class': 'form-control'}), forms.TextInput(attrs={'placeholder': 'Address Line 2', 'class': 'form-control'}), forms.TextInput(attrs={'placeholder': 'City', 'class': 'form-control'}), forms.TextInput(attrs={'placeholder': 'State', 'class': 'form-control'}), forms.TextInput(attrs={'placeholder': 'Postcode', 'class': 'form-control'}), ) super().__init__(widgets, attrs) def decompress(self, value): if value: return (value.address1, value.address2, value.city, value.state, value.postcode) return (None, None, None, None, None) Saving the form works as I want, but when re-entering the form in order to change values, it doesn't get prepopulated, although all other regular fields do. How do I get it to populate the field? -
Override the variable from parent class in Django Models
I have a model ChildModel and it has two parent classes ActivatorModel and TimeStampedModel Below are the three models: The two base classes class ActivatorModel(models.Model): """ ActivatorModel An abstract base class model that provides activate and deactivate fields. """ INACTIVE_STATUS = 0 ACTIVE_STATUS = 1 STATUS_CHOICES = ( (INACTIVE_STATUS, _('Inactive')), (ACTIVE_STATUS, _('Active')), ) status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=ACTIVE_STATUS) activate_date = models.DateTimeField(blank=True, null=True, help_text=_('keep empty for an immediate activation')) deactivate_date = models.DateTimeField(blank=True, null=True, help_text=_('keep empty for indefinite activation')) objects = ActivatorModelManager() class Meta: ordering = ('status', '-activate_date',) abstract = True def save(self, *args, **kwargs): if not self.activate_date: self.activate_date = now() super().save(*args, **kwargs) class TimeStampedModel(models.Model): """ TimeStampedModel An abstract base class model that provides self-managed "created" and "modified" fields. """ created = CreationDateTimeField(_('created')) modified = ModificationDateTimeField(_('modified')) def save(self, **kwargs): self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) class Meta: get_latest_by = 'modified' abstract = True The class using the above base models class ChildModel(ActivatorModel, TimeStampedModel): child_id = models.CharField( max_length=36, primary_key=True, default=uuid.uuid4 ) display_name = models.CharField(blank=True, max_length=100, null=True) status = models.CharField(max_length=20, null=True, blank=True, default='Active') The issues is whenever I try to save some character type value in ChildModel.status, it throws an error invalid input syntax for integer. How to properly override the variable status … -
Django Rest APi Authentication credentials
i am working on a project using Django as backed server and flutter as fronted framework , i faced a problem today when i try to POST a data from the flutter UI app into the Django server data base using the the REST API i keep getting this error "detail": "Authentication credentials were not provided." the problem is when i make a POST request from the web browser it works fine i guess i need to provide more information to the Django server to from the flutter App to authenticate then i can POST data here is the flutter method Future<CreateProduct> submitProduct(String name , String price , String brand , String countinstock , String category , String description) async { String createProductUri = "http://127.0.0.1:8000/api/products/create/"; final response = await http.post(Uri.parse(createProductUri),body: { "name": name, "price": price, "brand": brand, "countInStock": countinstock, "category": category, "description": description }); if (response.statusCode == 201){ final responseString = response.body; return createProductFromJson(responseString); } } and the Django request @api_view(['POST']) @permission_classes([IsAdminUser]) def createProduct(request): user = request.user data = request.data product = Product.objects.create( user=user, name=data['name'], price=data['price'], brand=data['brand'], countInStock=data['countInStock'], category=data['category'], description=data['description'], ) serializer = ProductSerializer(product, many=False) return Response(serializer.data) -
Keep sidebar open when reload page in django
I have multiple apps with templates in my django project. All the templates extend my base.html file, which include the page sidebar. When I click one of the menu on the sidebar the whole page is refreshed. How can I keep open the sidebar and only refresh the page content? I though about using ajax but I'm not sure if it is the right way. Here is the body part of my base.html. <body> <div class="wrapper"> <!-- SIDEBAR --> {% include 'sidebar.html' %} <!-- PAGE CONTENT --> <!--<div class="container-fluid">--> {% block content %} {% endblock %} <!--</div>--> </div> </body> And here is my sidebar.html <div class="sidenav"> <ul class="sidebar-nav"> <li><a href="#">Menu1</a></li> <li><a href="#">Menu2</a></li> <li><a href="#">Menu3</a></li> <li><a href="#">Menu4</a></li> <li><a href="#">Menu5</a></li> </ul> </div> -
How to properly build models in django
I want to implement a photo gallery in my project. in the django rest framework I want the output to be: [ { "id": 1, "owner": { "username": "drw", "first_name": "", "last_name": "", "avatar": "http://127.0.0.1:8000/media/default.png", }, "gallery": { "id": 4, "project_gallery": [ { "id": 1, "image": "http://127.0.0.1:8000/media/uploads/2022/8/9/drw/616da7a24f6856fab5dac79a_360_IT_Check_-_October_18th_2021_wUvme58.png", "thumbnail": null, "user": 1 }, { "id": 2, "image": "http://127.0.0.1:8000/media/uploads/2022/8/9/drw/Adapta-KDE-theme_vdDo0PO.webp", "thumbnail": null, "user": 1 }, { "id": 3, "image": "http://127.0.0.1:8000/media/uploads/2022/8/9/drw/Adapta-KDE-theme_ghZHmGF.webp", "thumbnail": null, "user": 1 } ], "project_gallery_name": "Testowo" }, "likes": [], "category": "ca1", "uuid": "30065e4d-3674-4f01-9861-307fe27ede13", "project_name": "Testowo", "comments": null } ] I do not know if I am doing well with manytomany. class ImagesForGallery(models.Model): user = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return 'User: {} || Image: {}'.format(self.user, self.image) class GalleryProject(models.Model): project_gallery_name = models.CharField(max_length=20, null=True, blank=True) project_gallery = models.ManyToManyField(ImagesForGallery, blank=True, related_name='project_gallery') def __str__(self): return '{}'.format(self.project_gallery_name) if i want an output like above then should i use many to many or foreginkey? -
Initialize request in get_edit_handler in ModelAdmin class in Wagtail
I can not inilitialize request in ModelAdmin. By default, request in function def get_edit_handler(self, instance, request) is None. How can I do it so I can access request in the function mentioned above? E.g for request.user. class SomemodelAdmin(ModelAdmin): model = Somemodel list_display = ("field",) edit_view_class = SaveContinueEditView def get_edit_handler(self, instance, request): print(request) #This prints None. -
Mezzanine + Cartridge 'Cart' instance needs to have a primary key value
Good afternoon. I just installed the cartridge to see its capabilities and got an error. Please help me solve this. [https://pastebin.com/tNuMbbQm][1] -
Django ModelChoiceField passes None
I'm very new to Django. I'm making form to add timetable to specific branch. So I have 'Branch' model and 'Timetable' model. 'Branch' model is in 'branches' app and 'Timetable' model is in 'schedules' app. What I'm expecting is when users fill in the form to add timetable, they can choose which branch to add it from select box. Here is my codes branches/models.py from django.core.validators import RegexValidator from django.db import models from django.urls import reverse # Create your models here. phone_validator = RegexValidator( regex="\d{2,4}-?\d{3,4}(-?\d{4})?", message="It's not correct phone number format.", ) class Branch(models.Model): srl = models.BigAutoField(primary_key=True, verbose_name="Serial") name = models.TextField(verbose_name="Branch name") postcode = models.CharField(max_length=5, verbose_name="Postcode") address1 = models.TextField(verbose_name="Road address") address2 = models.TextField(verbose_name="Detail address", blank=True) phone1 = models.CharField(max_length=13, validators=[phone_validator], verbose_name="Phone 1") phone2 = models.CharField(max_length=13, validators=[phone_validator], verbose_name="Phone 2", blank=True) is_opened = models.BooleanField(default=True, verbose_name="Is opened?") class Meta: verbose_name = "Branch" verbose_name_plural = "Branches" ordering = ["srl"] def __str__(self): return self.name def get_absolute_url(self): return reverse("branches:detail", kwargs={"srl": self.srl}) schedules/models.py import datetime from django.conf import settings from django.db import models class Timetable(models.Model): srl = models.BigAutoField( primary_key=True, verbose_name="Serial", ) branch_srl = models.ForeignKey( "branches.Branch", on_delete=models.CASCADE, verbose_name="Branch Serial", ) period = models.DecimalField( max_digits=2, decimal_places=0, verbose_name="Period", ) period_length = models.DurationField( default=datetime.timedelta(minutes=50), verbose_name="Period Length", ) is_holiday = models.BooleanField( default=False, verbose_name="Is … -
How can I add a "duplicate" button next to the "add another ..." button in djangos admin.StackedInline?
Is there a possibility to add a "copy" or "duplicate" button next to the "add another ..." button in djangos admin.StackedInline (see image)? It should add another object and prepopulate the fields based on the previous object (if that exists). Another fix could be to prepopulate the fields based on the previous object when adding it via "add another ...", but I don't know how to do that. -
how can i get the maximum value of each tag by day in the date range using django
I'am creating ListAPIView using DRF. Here is sample data. DateAndTime column measured per 10 seconds and range is 6/30-8/31. unfortunately, DateAndTime is CharField. Because the database design is like that. I sliced dateandtime field and i got slicedate column using annodate and Substr. The reason I did this was to do group by day. it works fine. I want to get the maximum value of each tag by day in the date range. The maximum value is duplicated, so I want to get the fastest time among them. I think my query is ok, but I get an error. please help me! DateAndTime TagName DataValue 2022-06-30 14:15:40 BW004_GD-4-16 99 2022-06-30 14:15:50 BW004_GD-4-16 25 2022-06-30 14:16:00 BW004_GD-4-16 99 2022-06-30 14:16:10 BW004_GD-4-16 50 2022-06-30 14:16:20 BW004_GD-4-16 99 2022-06-30 14:16:30 BW004_GD-4-16 99 . . . 2022-06-30 14:15:40 BW004_GD-4-17 50 2022-06-30 14:15:50 BW004_GD-4-17 40 2022-06-30 14:16:00 BW004_GD-4-17 25 . . . 2022-06-30 18:20:00 BW004_GD-4-17 50 2022-06-30 18:20:10 BW004_GD-4-17 50 2022-06-30 18:20:20 BW004_GD-4-17 10 . . . 2022-06-30 14:15:40 BW004_GD-4-18 30 2022-06-30 14:15:50 BW004_GD-4-18 40 2022-06-30 14:16:00 BW004_GD-4-18 100 . . . # models.py class EnvAi(models.Model): dateandtime = models.CharField(db_column='DateAndTime', blank=True, null=True) # Field name made lowercase. tagname = models.CharField(db_column='TagName', max_length=50, blank=True, null=True) # Field name … -
what is the best method to initialize or store a lookup dictionary that will be used in django views
I'm reviving an old django 1.2 app. most of the steps have been taken. I have views in my django app that will reference a simple dictionary of only 1300ish key-value pairs. Basically the view will query the dictionary a few hunderd to a few thousand times for user supplied values.The dictionary data may change twice a year or so. fwiw: django served by gunicorn, db=postgres, apache as proxy, no redis available yet on the server I thought of a few options here: a table in the database that will be queried and let caching do its job (at the expense of a few hundred sql queries) Simply define the dictionary in the settings file (ugly, and how many time is it read? Every time you do an 'from django.conf import settings'? This was the situation how it was coded in the django 1.2 predecessor of this app many years ago read a tab delimited file using Pandas in the django settings and make this available. the advantage is that I can do some pandas magic in the view. (How efficient is this, will the file be read many times for different users or just once during server startup?) prepopulate … -
I want to return multiple objects using django def get_context_data
def get_context_data(self, **kwargs): kcl = self.request.user.kcal men_kcal = 13.8 * kcl.weight context = super().get_context_data(**kwargs) if kcl.goal == 'diet': context['bmr'] = men_kcal - 500 else: context['bmr'] = men_kcal + 500 return context context['fixbmr'] = bmr * 2 I want to represent an object in the template. {{ bmr }} And {{ fixbmr }} I'd like to use. What should I do?