Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test OperationalError can't create table
When I'm trying to run my tests in django I get this error django.db.utils.OperationalError: (1005, 'Can\'t create table `test_grocerycheck`.`grocery_check_customuser_groups` (errno: 150 "Foreign key constraint is incorrectly formed")') This table is automatically created by AbstractUser. What should I do in this situation? -
How can I send only notification requests in docker
I am developing a website where there is a buyer and seller. They can chat each other. I know there is a library in django thats called Django channels. But I dont want to use it. I builded such a thing on my own. Every thing works fine. But when i try to integrate a notification system the server loads a lot. Everything seems. But I got a plan to solve this issue. But I dont know it will work. Thats why I am posting a qustion about the idea. For Notification system I requested GET method in every pages. So Is it possible to send all the reuqests to docker so that i could reduce the load. Or can someone give me an idea to solve this Issue? -
How to generate an XML file from serialized data?
I have created an endpoint following a tutorial which returns the response in XML format: class MyxmlRenderer(XMLRenderer): root_tag_name = 'License' item_tag_name = 'Details' class xmlView(APIView): renderer_classes = [MyxmlRenderer, ] def get(self, request): queryset = Details.objects.all() xml_serializer = DetailSerializer(queryset, many=True) return Response(xml_serializer.data) I was able to create json file from json_serialized data using: with open('data.json', 'w') as f: json.dump(json_serializer.data, f, indent=4) But I'm having difficulty in creating an xml file as xml_serializer data is of type ReturnList and not str. Any help would be greatly appreciated. Thanks. -
Why django form valdation error does not work in my form
I want to show user validation error but seems that this is not working in my login form here is the code my forms.py class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) remember_me = forms.BooleanField(required=False, label='Remember Me',help_text='Keep me logged in.',widget=forms.CheckboxInput()) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user doesn't exist") if not user.check_password(password): raise forms.ValidationError("Incorrect Password") if not user.is_active: raise forms.ValidationError("User no longer Active") return super(LoginForm,self).clean(*args,**kwargs) my views.py for login def my_login(request): if 'next' in request.GET: messages.add_message(request, messages.WARNING, 'To Continue, Please login here!') if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] remember_me = form.cleaned_data['remember_me'] user = authenticate(username=username, password=password) if user: login(request, user) if not remember_me: request.session.set_expiry(0) return redirect('accounts:home') else: request.session.set_expiry(1209600) return redirect('accounts:home') else: messages.info(request, 'Please check your credentials.') return redirect('accounts:login') else: form = LoginForm() return render(request, "login.html", {'form': form}) i know i am redirecting the form if form credential is wrong but if i don't i will throw error didn't return a httpresponse it return none instead also want to what is the best way to redirect or show exact validation error of which credential is wrong -
passs list to django template
hi I'm having a problem moving list in view.py to charts.html this is my view.py and my charts.py i'm not sure what the problem is the label data format is str and data is integer. Thanks in advance for your help -
Cannot resolve keyword 'phone' into field django
I added a new field name phone for phone number in my registration form, but now it throws error when i submit it throws Cannot resolve keyword 'phone' into field. Choices are: address, date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, notifications, order, password, profile, user_permissions, username this error i am using Django default usercreation forms here is my forms.py class SignUpForm(UserCreationForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{10}$', message="Inform a valid phone number.") email = forms.EmailField(max_length=254, required=True, help_text='Required. Inform a valid email address.') phone = forms.CharField(validators=[phone_regex], max_length=10, required=True, help_text='Required. Inform a valid phone number.') class Meta: model = User fields = ('username', 'email', 'phone', 'password1', 'password2',) def clean_email(self): email = self.cleaned_data['email'] qs = User.objects.exclude(pk=self.instance.pk).filter(email__iexact=email) if qs.exists(): raise ValidationError('A user with this email address already exists') return email def clean_phone(self): phone = self.cleaned_data['phone'] qs = User.objects.exclude(pk=self.instance.pk).filter(phone__iexact=phone) if qs.exists(): raise ValidationError('A user with same phone number already exists') return phone views.py class SignUpView(View): form_class = SignUpForm template_name = 'register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate … -
Django `output_type` for PostgreSQL row constructors
As part of some custom cursor-based pagination code, I'm expressing the below SQL that compares tuples/row constructors WHERE (col_a, col_b) > (%s, %s) ORDER BY col_a, col_b by using the Django ORM, and specifically using Func with alias, similar to this answer from django.db.models import F, Func, TextField col_a_col_b = Func(F('col_a'), F('col_b'), function='ROW', output_type=TextField()) col_a_col_b_from = Func(col_a_value, col_b_value, function='ROW') filtered_queryset = queryset .alias(col_a_col_b=col_a_col_b) .filter(col_a_col_b__gt=col_a_col_b_from) .order_by('col_a', 'col_b') It looks like for the Func, output_type is required, otherwise it throws the exception: Expression contains mixed types. You must set output_field It seems a bit odd to use TextField for this, but it works and I can see nothing better. Is there a more appropriate output_type to use, or a way to avoid having to set it? -
Django - User Registration with Modal Ajax
my user registration with modal form does not validate/save. It only just close immediately when you save and nothing happens. this is the views.py from django.template.loader import render_to_string from django.http import JsonResponse from authentication.forms import CustomUserCreationForm from django.contrib import messages def CreateUser(request): data = dict() if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() data["form_is_valid"] = True username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('home/manage-users.html') else: data["form_is_valid"] = False else: form = CustomUserCreationForm() context = {'form': form} data["html_form"] = render_to_string('partial_modal/create-user.html', context, request=request) return JsonResponse(data) Any tips how can I work this my code? Thank you. -
Gain time intervals in Django
I created a model in Django that records user visits to the product. I want to check if the user's previous visit, for example, was an hour ago, another visit is recorded in the model. How can I get this time interval ?? -
Templates does not exist
How to specify a path to base_site.html that would have views the blog saw it. enter image description here -
how to reference a foreign key when making a command
I am trying to make a custom command that I can call up within my Django project but am running into an issue referencing the foreign key it references. How do I correctly reference the created instance in order to complete the command? Any help would be appreciated. models.py class Client(models.Model): name = models.CharField(max_length=50) class Project(models.Model): schema_name = models.CharField(max_length=50) client = models.ForeignKey(Client, on_delete=models.CASCADE) command class Command(BaseCommand): help = ( "commands, --create_public" ) def add_arguments(self, parser): parser.add_argument( '--create_public', action='store_true', help='creates public tenant' ) def handle(self, *args, **options): if options['create_public']: # create your public tenant client = Client(name='client1') client.save() tenant = Project(schema_name='public', client='client1', ) tenant.save() error ValueError: Cannot assign "client": "Project.client" must be a "Client" instance. -
How to change default password reset email in djoser
I want to change the default email template of djoser for sending password reset email, I saw one answer in stackoverflow for changing the activation mail but i don't know how to use that for password reset email code to change default email for activation: base/reset_email.py from djoser import email class ActivationEmail(email.ActivationEmail): template_name = 'base/resetPasswordMail.html' settings.py DJOSER = { 'EMAIL': { 'activation': 'base.reset_email.ActivationEmail' }, } how to replace this code for password reset functionality -
Django heroku Image issue
I m new to Django and Heroku, I would like to know if I could in Django upload pictures in a specific folder in Cloudinary? and then recall them in my HTML files later ? I have seen this option online? model.py : background_image = CloudinaryField(null=True, folder='01-categories/') do you have any idea? how I could upload from my admin page and then that upload to Cloudinary and then recall in HTML pages ?? -
Filter by date in django
I am trying to filter the delivery instruction table by date. Especially only in Delivery Instructions, table data will be removed after 7 days after the creation. So in its model, I used DateTimeField as a date-time format. But in other models (e.g Part), I used DateField, and in views.py I write the same function as below and it works. But the issue with Delivery instructions is filtered by date is not working. filters.py class DIFilter(django_filters.FilterSet): created_date = django_filters.CharFilter( widget=forms.TextInput(attrs={ 'placeholder': 'YYYY-MM-DD'})) class Meta: model = DeliveryIns fields = ['product','supplier', 'created_date'] views.py def get_queryset(self): queryset = self.model.objects.all().order_by('-id') if self.request.GET.get('supplier'): queryset = queryset.filter(supplier_id=self.request.GET.get('supplier')) elif self.request.GET.get('product'): queryset = queryset.filter(product_id=self.request.GET.get('product')) elif self.request.GET.get('created_date'): queryset = queryset.filter(created_date=self.request.GET['created_date']) return queryset models.py class EventManager(models.Manager): def get_queryset(self): return super().get_queryset().filter( created_date__gte=timezone.now()-timezone.timedelta(days=7) ) class DeliveryIns(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) objects = EventManager() class Part(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) Can anyone help me out whats the matter? Thank you in advanced -
how to change host in django-robots?
I am struggling to add X-Robots-Tag I am using this library Django-robots and I have everything set as well, I am stuck on the hostname at sitemap showing example.com the documentation link https://django-robots.readthedocs.io/en/latest/# screenshot https://i.stack.imgur.com/GWUPu.png ''' #sitemaps.py class StaticViewsSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = "daily" def items(self): return [ 'home', ] def location(self, items): return reverse(items) class SnippetSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = "daily" def items(self): return Snippet.objects.all() #urls.py urlpatterns = [ ... path('<slug:slug>/', views.Snippet_detail), url(r'^robots1\.txt', include('robots.urls')), url(r'^sitemap1.xml$', cache_page(60*60*1)(sitemap), {'sitemaps': sitemaps}, name='cached-sitemap'), ... ] #models.py class Snippet(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(blank=True, null=True) body = models.TextField() def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return f'/{self.slug}/' ''' -
Crispy form not rendering on ModelForm
I am trying to render a ModelForm with crispy form but is not working,I have tried both tags: ( {{ form|crispy }} and {% crispy form %} ) Why doesn't work? models.py class ProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, unique=True) cover_image = models.ImageField(null=True, blank=True,upload_to='cover/') profile_image = models.ImageField(null=True, blank=True,upload_to='avatar/') def __str__(self): return self.user.username.title() forms.py class UploadCoverForm(forms.ModelForm): class Meta: model = ProfileInfo fields = ['cover_image'] def __init__(self, *args, **kwargs): super(UploadCoverForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) views.py @login_required def upload_cover(request): user = ProfileInfo.objects.get(user = request.user) if request.method == "POST": form = UploadCoverForm(request.POST, request.FILES, instance=user) if form.is_valid(): user = form.save(False) cover = form.cleaned_data.get("cover_image") if cover: image = Image.open(cover) image_data = BytesIO() image.save(fp=image_data, format=image.format) image_file = ImageFile(image_data) user.cover_image.save('{}.cover.{}'.format(user,image.format), image_file) user.save() return redirect("user:Profile", request.user.username) else: form = UploadCoverForm(instance=user) return render(request, "uploads/upload_cover.html",{"form": form}) I have included the link for bootstrap in "base_uploads.html" upload_cover.html {% extends "uploads/base_uploads.html" %} {% load crispy_forms_tags %} {% block title %} Upload Cover {% endblock %} {% block content %} <form method="POST" enctype="multipart/form-data" action="{% url 'user:upload_cover' %}"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary btn-md">Upload</button> </form> {% endblock %} settings.py INSTALLED_APPS = [ 'revealy_admin.apps.RevealyAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'channels', 'users', 'chats', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' Thanks -
how to set default hour for my django datetimefield
im trying to set default hour to my django datetimefield , im using datetime-local in my input , but it shows current time , i want to set default time to 12:00 PM and changeable as well i tried this but doesnt work from datetime import datetime def set_default_time_checkout(): now = datetime.now() new_time = now.replace(hour=12, minute=0, second=0, microsecond=0) return new_time class Booking(models.Model): check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(default=set_default_time_checkout,blank=True,null=True) but doesnt work and this is my forms.py class BookingForm(forms.ModelForm): check_in = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) check_out = forms.DateTimeField(initial=set_default_time_checkout, required=False,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) also the initial time doesnt work in the modelform is it possible please ? how to achieve it ? i tried these solutions from the question but none of them works Can I set a specific default time for a Django datetime field? thanks in advance -
OS Error: [WinError 123] when installed django in my python project
enter image description here i had build a simple blog project using Django. When i exit from my virtual env and again tried to run the project after activating virtual env ---- first issue i was facing that django not installed .... after that i run the command inside my project folder ablog "pip install django" and run the project i got this error... Previuosly also faced this error with one of my project python django... -
I am struggling to deploy my Django project (Django 3.1) on Heroku due to an incompatible build-pack after manually setting it to python
My first attempt was to just push to heroku without setting a default language manually: (myenv) ➜ quotatev3 git:(main) heroku create quotatev3 › Warning: heroku update available from 7.56.1 to 7.59.0. Creating ⬢ quotatev3... done https://quotatev3.herokuapp.com/ | https://git.heroku.com/quotatev3.git (myenv) ➜ quotatev3 git:(main) git push heroku main Enumerating objects: 370, done. Counting objects: 100% (370/370), done. Delta compression using up to 8 threads Compressing objects: 100% (321/321), done. Writing objects: 100% (370/370), 74.35 KiB | 5.31 MiB/s, done. Total 370 (delta 195), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to quotatev3. remote: To https://git.heroku.com/quotatev3.git ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/quotatev3.git' So after setting it manually I am getting an error on how my app is incompatible with the build-pack. (myenv) ➜ quotatev3 … -
django drf about many-to-many RelatedField custom field
I use the latest version of The Django REST Framework framework, and The table in model is many-to-many related My current model code looks like this: model.py class LvsDeploy(models.Model): MASTER = 'MASTER' BACKUP = 'BACKUP' ROLE_CHOICES = ( (MASTER, 'MASTER'), (BACKUP, 'BACKUP') ) id = models.AutoField(primary_key=True) cluster_name = models.CharField(max_length=30, verbose_name="cluster name") dip = models.CharField(max_length=15, verbose_name='DR IP') role = models.CharField(max_length=10, choices=ROLE_CHOICES, verbose_name="role") class LoadBalance(models.Model): id = models.AutoField(primary_key=True) lb_name = models.CharField(max_length=30, verbose_name='load balance') cluster = models.ManyToManyField('LvsDeploy',related_name='cluster') vip = models.CharField(max_length=50, verbose_name='VIP') port = models.IntegerField(verbose_name='port') def __str__(self): return self.lb_name My serializer code looks like this: serializers.py class LvsDeployReadOnly(serializers.ModelSerializer): class Meta: model = LvsDeploy fields = '__all__' class LoadBalanceSerializer(serializers.ModelSerializer): cluster_name = serializers.RelatedField(source='cluster.name',read_only=True,default='abc') cluster = LvsDeployReadOnly(many=True) ##rs = RSInfoSerializer(many=True, read_only=True) class Meta: model = LoadBalance fields = '__all__' ##extra_fields = ['rs','cluster','cluster_name'] extra_fields = ['rs','cluster','cluster_name'] My views code: class BalanceList(views.APIView): def get(self, request): queryset = LoadBalance.objects.all() serializer = LoadBalanceSerializer(queryset, many=True) print(serializer.data) return Response(serializer.data) and request actual output: [ { "id": 2, "cluster_name": null, "cluster": [ { "id": 1, "cluster_name": "lvs_sz01", "dip": "1.1.1.6", "role": "BACKUP", }, { "id": 2, "cluster_name": "lvs_sz01", "dip": "1.1.1.5", "role": "BACKUP", } ], "lb_name": "lb001", "vip": "1.1.1.1", "port": 80, } ] the cluster_name filed value is same in the dictionary of lists . But … -
How to pass the tests after modifying the model group?
I modified the Django model Group to add 2 extra fields. Unfortunately, since then, no more unit tests are working. django.db.utils.OperationalError: no such column: auth_group.description I added this code in my model: Group.add_to_class('description', models.TextField(null=True, blank=True)) Group.add_to_class('client', models.ForeignKey( "client.Client", verbose_name="client", related_name="group_client", on_delete=models.CASCADE, null=True, blank=True )) I think that the migration file is not taken for the tests. How can I integrate it? -
getting empty dictionary on POST ajax
I am trying to delete some elements in database when user clicks on delete icon but as i am sending id through POST request , i am getting empty dictionary , {% for skills in seeker_skills %} <div class="col-md-4"> <button class="btn btn-info mx-2">{{skills.skill_name}}<span class="badge badge-dark ">{{skills.skill_level}}</span></button><span><i class="fas fa-trash-alt delete_skill" data-attr={{skills.id}} style="cursor: pointer;"></i></span> </div> {% endfor %} Ajax code $.ajax({ url:'/delete_skill/', method : 'POST', data: { skill_id:value }, dataType: "json", contentType: "application/json", success :function(data){ console.log(data) contain_label.remove() contain_icon.remove() } , error:function(e){ console.log(e) My view @csrf_exempt def delete_skill(request): if request.method == 'POST': data = {} print('method is post') job_id = request.POST.get('skill_id') print(job_id) try: Job_Skillset.objects.get(id=job_id).delete() data['status'] = 'deleted' except ObjectDoesNotExist: data['status'] = 'nodata' return JsonResponse(data,safe=False) -
How to display django roles and permissions in a custom dashboard
I am trying to have roles, groups, and permissions in my custom admin dashboard (not the django admin) so as to assign roles, groups, and permissions. The django admin page for permissions looks like the image below. I want to have exact same permissions in my template. In other frameworks like laravel, they have it done beautifully with the Spatie package. Is there any similar package too in Django or I have to write every single logic myself. Or better still can I query the Django-admin permissions and groups and display them in my custom admin dashboard template. -
how to get tags from user in form and save it to database in django
I have a form that gets some fields and tags from users and save the user input data in database: By the way I am using taggit this is my model: from taggit.managers import TaggableManager class Question(models.Model): title = models.CharField(max_length=500) name = models.CharField(max_length=50, default=None) slug = models.SlugField(max_length=500, unique_for_date='created', allow_unicode=True) body = models.TextField(max_length=2000) created = models.DateTimeField(auto_now_add=True) tags = TaggableManager() def get_absolute_url(self): return reverse("questions:question_detail", args=[self.created.year, self.created.month, self.created.day, self.slug]) def __str__(self): return self.title and here is my view: def question_form(request): new_question = None if request.method == 'POST': question_form = QuestionForm(data=request.POST) if question_form.is_valid(): new_question = question_form.save(commit=False) new_question.slug = slugify(new_question.title) new_question.save() question_form.save_m2m() else: question_form = QuestionForm() return render(request, 'questions/que/form.html', {'question_form':question_form, 'new_question':new_question}) and my form.py is like this: from taggit.forms import TagField class QuestionForm(ModelForm): class Meta: model = Question fields = ('name', 'title', 'body',) tags = TagField() my problem is when user enters the tags and other fields everything is saved in database except the tags! Can anyone help me? -
'method' object does not support item assignment
I am trying to count likes on each post and this is my model. But I am getting error on the item detail page likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() VIEW: class ItemDetailView(DetailView): model = Item template_name ='waqart/item_detail.html' def get_context_data(self, *args, **kwargs): context = super(ItemDetailView, self).get_context_data stuff = get_object_or_404(Item, id=self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes']= total_likes return context