Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
trying to send email with python and django
So I am trying to send email with python in a django view problem is everything inside my own server localhost is ok but in production it just dont like to work and I dont know why here is the code @api_view(["PUT"]) @permission_classes([IsAuthenticated]) def updateOrderToPaid(request, pk): order = Order.objects.get(taransId=pk) orderItems = OrderItem.objects.filter(order=order).all() address = ShippingAddress.objects.get(order=order) smtp_server = "smtp.gmail.com" port = 465 sender_email = "MYGMAIL" password = "MYPASSWORD" receiver_email = "RECEIVERGMAIL" message = MIMEMultipart("alternative") message["Subject"] = "DONE" message["From"] = sender_email message["To"] = receiver_email context = ssl.create_default_context() text = """\ ITS WORKING """ html = """\ <html> <body> <p class="text-danger">Done!</p><br> <ul>\n """ html += "\n".join(["<li>" + str(s) + "</li>" for s in orderItems]) html += f""" \n</ul> </body> </html>""" part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) data = { 'pin' : 'SOME_PIN', 'amount' : int(order.TotalPrice), 'transid' : order.taransId } try: response = requests.post('https://panel.aqayepardakht.ir/api/verify', data = data) if response.status_code == 200 and response.text == '1': order.isPaid = True order.paidAt = datetime.now() order.save() return Response({"message": "پرداخت با موفقیت انجام شد"}, status=status.HTTP_200_OK) with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string()) elif response.status_code == 200 and response.text =='0': print(response, "else if error") return Response({"details": "تراکنش با موفقیت انجام نشد"}, status=status.HTTP_400_BAD_REQUEST) … -
"Could not parse some characters" in Crispy Form Django
I have a checkbox to filter the data in the template. While I have a field name which is having space in between words something like this: Dual Channel. I'm getting errors like this: Could not parse some characters: formChannel.Dual| Channel||as_crispy_field While when I have field names like single words then there is no problem for eg: Dual. but when I have words more than one, then it shows the above error. for eg: Dual Channel This is my template code: <form action="{% url 'main:other' %}" method="POST"> {% csrf_token %} {{ formChannel.Dual Channel|as_crispy_field }} </form> views.py if request.method == 'GET': formChannel = Form() elif request.method == 'POST': formChannel = Form(request.POST) if formChannel.is_valid(): channel_names = [] for channel_name in formChannel.cleaned_data: if formChannel.cleaned_data[channel_name] == True: channel_names.append(channel_name) if channel_names: channel = Channel.objects.filter(channel__in=channel_names) How to get rid out of this problem in Django crispy form -
Django form with queryset
I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. Which it does with a signal, @receiver(post_save, I am trying to save the value. But the problem is with my form.py. In my forms.py I filter away assets that are not allowed to be loaned and assets that are loaned at the moment. That gives a problem when I try to edit/update it. Because the form does filter away it's own items. asset = forms.ModelChoiceField(required=False, queryset=Asset.objects.filter(Q(is_loaned=False) & Q(may_be_loaned=True)), label="Asset", widget=forms.Select(attrs={'class': 'form-control'})) forms.py class Loan_assetForm(forms.ModelForm): loaner_name = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaner name'})) location = forms.ModelChoiceField(queryset=Locations.objects.all(), label="Asset loaned form", widget=forms.Select(attrs={'class': 'form-control'})) loaner_address = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaners address'})) loaner_telephone_number = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaner telephone number'})) loaner_email = forms.EmailField(label="", max_length=100, widget=forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Loaners email'})) loaner_quicklink = forms.URLField(label="", max_length=100, required=False, widget=forms.URLInput( attrs={'class': 'form-control', 'placeholder': 'Quicklink'})) loaner_type = forms.ModelChoiceField(queryset=Loaner_type.objects.all(), label="Loaner type", widget=forms.Select(attrs={'class': 'form-control'})) … -
my change password forms error is not working in my html page
my html form is {% if messages %} {% for message in messages %} <div class="alert alert-danger" role="alert"> <strong>{{message}}</strong> </div> {% endfor %} {% endif %} {% if form.errors %} {% for field in form %} {% for error in field.error %} <div class="alert alert-danger" role="alert"> <strong>{{error|escape}}</strong> </div> {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger" role="alert"> <strong>{{error|escape}}</strong> </div> {% endfor %} {% endfor %} {% endif %} my views.py when i enter wrong passwords its redirect me to same page , if i not return the else part of is_valid it giving me object return error. what can i do for showing form error in frontend def change_password(request): if request.user.is_authenticated: if request.method == "POST": form = PasswordChangeForm(request.user , request.POST) if form.is_valid(): user = form.save update_session_auth_hash(request , user) messages.success(request , "Your password is successfully changed") return redirect('index') else: messages.error(request , "Please correct the error below.") return redirect('change_password') else: form = PasswordChangeForm(request.user) return render(request , "change-password.html" , {'form':form}) else: messages.error(request , "Please login to see that page") return redirect('login') -
HttpResponse with JsonResponse for showing detail object django
i'm trying to show detail page which is JsonResponse @login_required def booking_detail_lists(request,id): obj = get_object_or_404(Booking.objects.annotate(no_persons=Count('takes_by')),id=id) bookingvisitors = BookingVisitor.objects.filter(booking=obj) doc = Document.objects.filter(booking=obj) documents = [] for i in doc: documents.append({ 'source':i.docs.url }) visitors = [] for i in bookingvisitors: visitors.append({ 'full_name':i.visitor.full_name, 'reason':i.reason, 'check_in_vis':i.check_in_vis, 'check_out_vis':i.check_out_vis, 'admin':i.admin.username, 'date':i.date }) data = { 'check_in':obj.check_in, 'check_out':obj.check_out, 'taker':obj.taker, 'phone':obj.phone, 'no_person':obj.no_persons, 'id':obj.id, 'takes_by':visitors, 'images':documents, } return JsonResponse({'data':data}) object lists def lists(request): lists = Booking.objects.all() return render(request,'lists.html',{'lists':lists}) lists.html to redirect to booking_detail_lists {% for i in lists %} <button><a href="{% url 'booking:booking_detail_lists' i.id %}"><i class="fas fa-file-invoice"></i></a></button> {% endfor %} my urls.py path('ajax/booking/<int:id>',booking_detail_lists , name='booking_detail_lists'), in this template i want to show booking_detail_lists view $.ajax({ type:'GET', url:"{%url 'booking:booking_detail_lists' %}" success:function(data){ //add some data into html content } }) <!--some html content--> but i dont know how to give object id to {%url 'booking:booking_detail_lists' %}! and also i'm not sure how to render the json data with http response -
Return redirect with query paramters in Django
Using django-filter a user can set a specific filter. If the user then decides to delete a product with that filter, I would like to return the same page with the given filter applied. Right now I'm using a delete-view to handle the deleting class WishlistProductDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView): model = WishlistProductPrices success_url = "my_wishlist" context_object_name = "links" def test_func(self): """ Check if the logged in user is the one created the link """ link = self.get_object() #Gets the current link if self.request.user == link.user: return True return False def get_success_url(self): messages.success(self.request, "Product was removed") return reverse_lazy("my_wishlist") #Parse the filter parameters to "my_wishlist" The view for generating the HTML where the deleting occurs is the following: @login_required def my_wishlist(request): user = request.user user_products = WishlistProductPrices.objects.filter(user=user).all() ### Create filters ### filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) if request.method == "POST": post_form = AddWishlistForm(request.POST) if post_form.is_valid(): messages.success(request, "Thanks a lot!") filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) form = AddWishlistForm() context = { "form":form, "filter":filter } return redirect("my_wishlist") #How to add parameters to else: #Some irrelevant stuff else: #Get request form = AddWishlistForm() context = { "form":form, "filter":filter } return render(request, "discounttracker/add_wishlist.html",context=context) As a comment in [this][1] SO answer I'm thinking about … -
How to upload photos to a fle in m'y computer using Django reste framework
I created a photo model, serializer and view, Users Can upload photos to m'y website. I learned that thé best solution to do it is to upload thé photo on thé computer and the path on data base. But how Can i upload thé photo to my computer via my website or my api ? Modèles.py ken authentification. So for adding an Announcement the user must be authenticated. Models.py class User(AbstractUser): username = None email = models.EmailField(max_length=100, verbose_name='email', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Announcement(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) photo = models.ManyToManyField(Photo, blank=True) class Photo(models.Model): name = models.CharField(max_length=100) content_type = models.CharField(max_length=100) path = models.CharField(max_length=100) Serializers.py class AnnouncementSerializer(serializers.ModelSerializer): author = UserSerializer(required=True) parameters = ParameterSerializer(many=True, required=False) photo = PhotoSerializer(many=True, required=False) class Meta: model = Announcement fields = ['id', 'name', 'author', 'parameters', 'photo'] class UserSerializer(serializers.ModelSerializer): photo = PhotoSerializer() class Meta: model = User fields = ['id', 'email','photo', ] class ParameterSerializer(serializers.ModelSerializer): class Meta: model = Parameter fields = '__all__' class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo fields = '__all__' Views.py class AnnouncementCreate(CreateAPIView): permission_classes = [IsAuthenticated] queryset = models.Announcement.objects.all() serializer_class = AnnouncementSerializer -
Django `LookupError: App 'accounts' doesn't have a 'User' model` causes AUTH_USER_MODEL fails with `accounts.User` has not been installed
I am trying to refactor an existing code base by creating new accounts app with new custom User model. When I try to do makemigrations, I get the following error: Traceback (most recent call last): File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/config.py", line 268, in get_model return self.models[model_name.lower()] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/auth/__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/config.py", line 270, in get_model raise LookupError( LookupError: App 'accounts' doesn't have a 'User' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dev/Projects/Foto-Dino/foto-dino/manage.py", line 22, in <module> main() File "/home/dev/Projects/Foto-Dino/foto-dino/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen … -
Django_filters Reverse foreign key relationship lookup
I am working on an application and recently trying to figure out how to use the reverse foreign key relationship lookup in django filters. models.py class Units(models.Model): Unit = models.CharField(primary_key=True, max_length=200, null=False, unique=True) Type = models.CharField(max_length=200,null=True) Floor = models.CharField(max_length=200, null=True) Building = models.CharField(max_length=200, null=True) def __str__(self): return str(self.Unit) # Keeps track of the inventory updates class Inventory(models.Model): Unit = models.ForeignKey(Units, on_delete=models.CASCADE, null=True, to_field="Unit") Price = models.IntegerField(null=True) Status= models.CharField(max_length=200, null=True) Cancelations_Swaps = models.CharField(max_length=200, null=True) Date_of_update = models.DateField(default=timezone.now) Custumer = models.ForeignKey('Lead', on_delete=models.CASCADE, null=True, to_field="id") def __str__(self): return str(self.Unit) I am displaying in my template all the units with theire latest Status (filtering on Date of update) using the tag bellow @register.filter_function def fil(i): if i.inventory_set.all().order_by('-Date_of_update'): status=i.inventory_set.all().order_by('-Date_of_update')[0].Status return status else: return False and the template is as follows: template {% for i in Unit %} <tr> <td> {{i.Unit }}</td> <td> {{i.Type }}</td> <td> {{i.Floor }}</td> <td> {{i.Building }}</td> <td>{{i|fil}}</td> Where Unit is simply Units.objects.all() I also have built a filter in order to filter the data diplayed as follows: class Unitfilter(django_filters.FilterSet): class Meta: model = Units fields = '__all__' filter_overrides = { models.CharField: { 'filter_class': django_filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'icontains', }, } } I want to be able to filter the … -
For loop in Django templates
I want to display the center of a for loop, for example i for loop the 1-30 then i want to for loop the 11-20 here is the example of how i use the for loop in my html: this is method that i used when i for loop to 30-20 {% for category in category_list reversed %} {% if forloop.counter < 11 %} <li><a class="dropdown-item" href="home/category/{{category.name}}">{{ category.name|title }}</a></li> {% endif %} {% endfor %} this i the method when i for loop to 1-10 {% for category in category_list %} {% if forloop.counter < 11 %} <li><a class="dropdown-item" href="home/category/{{category.name}}">{{ category.name|title }}</a></li> {% endif %} {% endfor %} problem how to for loop the 11-20? thanks for the help! -
Django + PostgreSQL: pagination extremely slow for millions of objects
I have around 6 million objects in my database. For these objects, I need to have a structure page, where the users would browse through the aforementioned 6 million objects as paginated content. My code for the pagination is a total duplicate of what is given in the documentation of Django: def listing(request): movie_list = Movie.objects.all() paginator = Paginator(movie_list , 100) # Show 100 movies per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'movies.html', {'page_obj': page_obj}) Howevre, most of the resulting 60,000 pages with the movies are too long to open, and give 504 timeout errors, which also results in the content being unreadable for GoogleBot (which is actually the main aim of the structure page). What can be the turnaround to prevent these timeouts and ensure the normal load speed for the large paginated content in Django? The database I am using is PostgreSQL. -
send contents of csv from react to django backend
Any advise on how i can get my backend (django) to receive and further process the csv contents sent from react? FrontEnd- import Papa from "papaparse"; export default function App() { return ( <div className="App"> <input type="file" accept=".csv" onChange={(e) => { const files = e.target.files; console.log(files); if (files) { console.log(files[0]); Papa.parse( files[0], { header:true, skipEmptyLines: true, complete: function (results) { console.log("Finished:", results.data); } } ); } }} /> </div> ); } Backend - Standard Django framework -
Django admin how to order by model property?
I have a model with property and I want to be able to sort instances in the admin panel by that property. My model with _points property: class CustomUser(models.Model): inviter = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) @property def _points(self): res = TelegramUser.objects.filter(inviter_id=self.id).count() return res -
Form errors not displaying with Django Crispy Forms
I just started learning Django and Python some weeks back. Working on a project sign up page, everything works perfectly except that form errors are not displaying on the form itself but redirected to a debug error page with the below ValidationError at /register/ ['Username exists'] Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 3.2.5 Exception Type: ValidationError Exception Value: ['Username exists'] During a new user profile registration, i am checking if the username used to register already exists or not and if it exists, i want to display an error to user that Username already exists. Please see my code below: forms.py class RegistrationForm(forms.Form): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') username = forms.CharField(label='Username') password = forms.CharField( label='Password', widget=forms.PasswordInput(), min_length=8) password_confirm = forms.CharField( label='Confirm Password', widget=forms.PasswordInput()) email_address = forms.EmailField(label='Email') phone_number = PhoneNumberField(label='Phone Number') whatsapp_number = PhoneNumberField(label='WhatsApp Number', required=False) COUNTRY_CHOICES = [ ('', 'Choose...'), ] country = forms.ChoiceField(label='Country', choices=COUNTRY_CHOICES) referral_id = forms.CharField(label='Referral ID', required=False) license_agreement = forms.BooleanField( label='I agree to all the Terms and Conditions') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'create-account-form' self.helper.form_action = 'register' self.helper.form_show_errors = True self.helper.layout = Layout( Row( Column('first_name'), Column('last_name'), css_class='g-2' ), Row( Column( PrependedText('username', '@') ), Column('country'), css_class='g-2' ), … -
Python Django website for task Scheduling
I am creating a website for my College Project using Python Django Framework for Task Scheduling.Every user creates their own account.I am asked to add a functionality that when a user logs in with its credentials, the user must get suggestions from it's past experience for eg" you scheduled task for drinking water on sunday at 10:30 am, so would you like to add it to the schedule now?". So I want to know How I can achieve this ? and Feature is same for all users but each user gets suggestions based on it's own data.Please let me know about the same in Detail. -
How do I auto select group name in particular group post, i have done with authenticated user auto select
I am trying auto select group name based on in which group user want to post, if user in particular group details page. when he click post . the form will auto select group name... this is my post model: class Posts(models.Model): groups_name = models.ForeignKey(Groups, related_name='posts', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='my_posts', on_delete=models.CASCADE) post_body = models.TextField(blank=True,null=True) post_image = models.ImageField(upload_to='images/posts/', blank=True, null=True) post_created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) + ' |' + str(self.groups_name) def post_name(self): return self.post_body[:1000] def get_absolute_url(self): return reverse("groups:group_detail", kwargs={"slug": self.groups_name.slug}) class Meta: ordering = ["-post_created"] this is my view: class CreateGroupPost(LoginRequiredMixin, CreateView): model = Posts form_class = GroupPostCreateForm login_url = '/account/login/' template_name = 'groups/addpost_group.html' this is my urls.py: app_name = 'groups' urlpatterns = [ path('', GroupListView.as_view(), name='group_list'), path('create_group/', GroupCreateView.as_view(), name='create_group'), path('<str:groups_name>/create_grouppost/', CreateGroupPost.as_view(), name='create_grouppost'), path('group_detail/<slug>', GroupDetailView.as_view(), name='group_detail'), path('group_update/<slug>', GroupUpdateView.as_view(), name='group_update'), path('join/<slug>/', Joingroup.as_view(), name='join_group'), path('leave/<slug>/', LeaveGroup.as_view(), name='leave_group'), ] this is group_details.html i gave url link to add post: {% if user in groups.members.all %} <div class="d-grid gap-2 mt-3"> <a href="{% url 'groups:create_grouppost' groups.groups_name %}" class="btn btn-primary">Create Post</a> </div> {% else %} <div class="d-grid gap-2 mt-3"> <a class="btn btn-primary" href="{% url 'groups:join_group' groups.slug %}">Join Group</a> </div> {% endif %} this is my add_post.html page add post page -
image not updating in django from form post request
I am trying to edit an object through the form All fields are edited but the image field does not change What is the problem? model created with signals when user create account template <div> <form action="{% url 'user:profile' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="submit"> </form> </div> model class Profile(models.Model): CHOICES = ( ('RE', 'مشاور املاک'), ('S', 'فروشنده'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) real_estate = models.OneToOneField(Business , related_name='business' ,on_delete=models.CASCADE, blank=True , null=True) image = models.ImageField(blank=True) type_of_user = models.CharField(max_length=300, choices=CHOICES) phone_number = PhoneNumberField(unique = True, null = False, blank = False) form class ProfileForm(ModelForm): class Meta: model = Profile fields = ['type_of_user' , 'phone_number' , 'image'] views def profile(request): profile = Profile.objects.get(user=request.user) if request.method == 'POST': form = ProfileForm(request.POST , instance=profile) profile = form.save(commit=False) profile.user = request.user profile.save() redirect('busi:index') else: form = ProfileForm() context = { 'profile':profile, 'form':form } return render(request , 'user/profile.html' , context) -
is there anyway to accept dogecoin or TRX to website (django)
I am on project where I have to implement crypto Wallet to perform dogecoin or tron transactions but I have never worked with crypto wallets nor I have any idea , so can someone suggest me how to integrate it with some steps please. thank you -
django.core.exceptions.ValidationError: ['“Undergraduate” is not a valid UUID.']
I'm trying to add a way for a user to select if they are a undergrad or grad student in my models.py. Everything works except when I added this code below: undergrad_or_grad = models.OneToOneField( 'StudentStatus', default="Undergraduate", on_delete=models.CASCADE) Basically my thought process was, if the user doesn't select an option, they'll just be defaulted as an undergrad type student. Below is my full models.py file. from django.db import models from django.contrib.auth.models import User import uuid from django.db.models.signals import post_save, post_delete class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) profile_picture = models.ImageField( null=True, blank=True, upload_to='profiles/', default='profiles/defaultProfile.jpeg') username = models.CharField( max_length=200, null=True, blank=True, unique=True) name = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=1000, null=True, blank=True) undergrad_or_grad = models.OneToOneField( 'StudentStatus', default="Undergraduate", on_delete=models.CASCADE) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) class StudentStatus(models.Model): STUDENT_TYPES = ( ('undergrad', 'Undergraduate'), ('grad', 'Graduate'), ) title = models.CharField(max_length=200, null=True, blank=True, choices=STUDENT_TYPES) date_created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.title) Here's my full error after I run python manage.py makemigrations and then python manage.py migrate. I tried getting rid of default="Undergraduate" but the error still persists. (env) PS D:\Django Projects\StudentArchive> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, users Running … -
Raw Query to Django ORM Query
I have these two models: class Project(models.Model): name = models.CharField(max_length=200) class ProjectAdditionalInfo(models.Model): project = models.OneToOneField(Project) info = models.TextField() The Raw SQL is: select * from project_projectadditionalinfo A left join project_project B on A.project_id=B.id where B.id is null What will be the django query in response to the raw sql provided? Thanks in Advance. -
Deletion of an object in SQLite3 outputs a different error than Postgres
I have a Django and pytest-django project and I'm encountering a weird issue. My prod env has a Postgres DB and when running local tests I use SQLite3. Our DB schema look like this class A(BaseModel): # Some properties class B(BaseModel): a = models.ForeignKey(A, on_delete=DO_NOTHING, null=False) # Some other properties Assuming I have 2 objects (a which is an instance of A, and b which is an instance of B), deleting object a before deleting b will raise the following error on Postgres: django.db.utils.IntegrityError: update or delete on table \"db_a\" violates foreign key constraint \"db_a_id_32c056c8_fk\" on table \"db_b\" However, running the same code locally, using the (in-memory version of) SQLite, will raise: django.db.utils.IntegrityError: The row in table 'db_b' with primary key '453c667321254983915068259f6a999f' has an invalid foreign key: db_b.a_id contains a value 'b8fd641710be466ca8eab451faaed757' that does not have a corresponding value in db_a.id. So, in both cases, the deletion operation will output an error - but not the same one. I have no issues with the fact that an error is raised, but I would like my local unit tests to have the same error outputted as my remote one without changing the DB locally to PG. Any insights into this behaviour, … -
Image Gallery paginate through pure JavaScript
Django Here is my Django Template, to fetch images from database through {% for Nslide, Products, range in allProducts %}, now I want to pagination for each three Carousel using pure JavaScript no jQuery, how it's possible? I searched a lot but all the solution are based on Array, or tables not for Gallery. Thanks.. {% for Nslide, Products, range in allProducts %} <div id="carousel{{forloop.counter}}" class="carousel slide carousel-fade" data-bs-ride="carousel"> <ul class="carousel-indicators"> <button type="button" data-bs-target="#carousel{{forloop.counter}}" data-bs-slide-to="0" class="active"></button> <!-- Start of Range forloop --> {% for i in range %} <button type="button" data-bs-target="#carousel{{forloop.parentloop.counter}}" data-bs-slide-to="{{i}}"></button> {% endfor %} <!-- End of Rang forloop --> </ul> <!-- Start of Div => pricing --> <div class="pricingdiv" id="slider-wrapper"> <div class="carousel-inner "> <!-- Start of Carousel-item Active --> <div class="carousel-item active"> <!-- Start of (Product) forloop --> {% for i in Products %} <!-- Start of Div (Col) --> <div class="col-xs-3 col-sm-3 col-md-3 p-2 mt-3 reveal"> <!-- Start of Div (productHover) --> <div class="productHover gallery-items"> <div class="card card-body"> <img src='{{i.Product_Image}}' class="xzoom rounded-circle border card-img-top" /> <!-- start Div (card-body) --> <div class="card-body"> <h5> <strong> <a class="dark-grey-text">{{i.Product_name}}</a> </strong> </h5> <p class="card-text">{{i.Product_Description}}</p> <div class="row"> <div class="col-sm-12 "> <button id="pr{{i.id}}" class="btn btn-primary btn-sm shoppingCart" onclick="('productId = {{i.id}}')">Add to Cart</button> </div> … -
Why Django Channels test suites and consumers are using different databases?
Today, I ran into a problem with Django channels. I noticed that my test suites and and my consumers are using different databases. For example if I create a fake User object (for authentication) in my test suites, My consumer doesn't have access to that fake user. When I inspected the value of User.objects.all() inside my test suite, I got my fake user in the queryset but when I evaluated the same expersion inside my consumer's connect method, I got my real users in the original database which clearly shows that my consumer is not using the test database but it is using the original database. I wanted to know why my consumer is using the original database instead of the test database which is supposed to contain fake data for testing purposes? Here are all the packages I have installed: aioredis==1.3.1 asgiref==3.4.1 async-timeout==3.0.1 attrs==21.2.0 autobahn==21.3.1 Automat==20.2.0 autopep8==1.5.7 certifi==2021.5.30 cffi==1.14.6 channels==3.0.4 channels-redis==3.3.0 charset-normalizer==2.0.4 constantly==15.1.0 cryptography==3.4.7 daphne==3.0.2 Django==3.2 django-cors-headers==3.7.0 django-crum==0.7.9 django-extensions==3.1.3 django-filter==2.4.0 django-random-queryset==0.1.3 django-schema-graph==1.2.0 django-spaghetti-and-meatballs==0.4.2 djangorestframework==3.12.4 djangorestframework-recursive==0.1.2 djangorestframework-simplejwt==4.6.0 drf-spectacular==0.15.1 factory-boy==3.2.0 Faker==8.10.2 gunicorn==20.1.0 hiredis==2.0.0 hyperlink==21.0.0 idna==3.2 incremental==21.3.0 inflection==0.5.1 jsondiff==1.3.0 jsonschema==3.2.0 Markdown==3.3.4 msgpack==1.0.2 Pillow==8.2.0 psycopg2-binary==2.8.6 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.7.0 pycparser==2.20 PyJWT==2.1.0 pyOpenSSL==20.0.1 pyrsistent==0.18.0 python-dateutil==2.8.2 python-dotenv==0.15.0 pytz==2021.1 PyYAML==5.4.1 requests==2.26.0 service-identity==21.1.0 six==1.16.0 sqlparse==0.4.1 text-unidecode==1.3 toml==0.10.2 Twisted==21.7.0 … -
django custom tags that returns a boolean - using in a boolean expression in template results in "Unused 'foo' at end of if expression."
I am using Django 3.2 I am writing custom template tags for my project. This is some of my code: /path/to/myapp/templatetags/wanna_be_starting_something.py @register.simple_tag(name='can_dance_with', takes_context=True) def can_dance(context, danceable_object): request = context['request'] user = request.user if isinstance(danceable_object, Danceable): return danceable_object.can_dance(user) return False /path/to/myapp/templates/myapp/dancing.html {% load wanna_be_starting_something %} {% if can_dance_with nicegirl %} <div class="col">Nice!</div> {% else %} <div class="col">Oh Dear!</div> {% endif %} When I run the HTML above, I get the error message: Unused 'nicegirl' at end of if expression. If I remove the if conditional - it runs fine. How can I write a custom tag that returns a boolean that can be used in conditional expressions in the calling template? -
Overriding templates with Django 3.2.6
I am new to python and working through a Zero to Hero course by Mosh on YouTube. I am getting stuck on a problem, and even after going through all the Django documents (https://docs.djangoproject.com/en/3.2/howto/overriding-templates/) I just can't see where I am going wrong. I have tried pasting the file path for the base.html file directly, as well as other methods such as os.path.join(BASE_DIR, 'templates') to try find the right path. But I still get an error. Here is what I think all the code someone would need to understand the problem. Sorry if I have copied too much, but I am not sure what I actually need to show for someone to fully understand where I might have gone wrong. The overall project is call PyShop and I have a file called index.html which is located in PyShop\products\templates\index.html which is trying to call the base.html file by {% extends 'base.html' %}. The base.html file is located here PyShop\templates\base.html. When I run I get the below error. If I move the base.html file out from under the templates folder and just have it on it's own like this PyShop\base.html ie not in any subfolder then it works no problem. TemplateDoesNotExist at …