Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - can't download file (showed as text instead)
I have a pdf in my static files, I need to add it some text and let the user download it, but the download part gives me some problems, here is part of my code: views.py import io from werkzeug.wsgi import FileWrapper from pathlib import Path from PyPDF2 import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from django.http import HttpResponse, FileResponse def downloadpdf(request): pdf_path = (Path.home()/"bot"/"mysite"/"static"/"images"/"tesseragenerica.pdf") # 1 pdf_reader = PdfFileReader(str(pdf_path)) packet = io.BytesIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) testo = "text to add" #in future "text to add" will be the username can.drawString(5, 5, testo) can.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(open("/home/myusername/bot/mysite/static/images/tesseragenerica.pdf", "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) # finally, write "output" to a real file outputStream = open("destination3.pdf", "wb") output.write(outputStream) outputStream.close() return FileResponse(FileWrapper(packet), as_attachment=True, filename='hello.pdf') The code for adding text to pdf is correct because in local it works so i think the problem is what i'm putting as the first argument of FileResponse, if I put FileWrapper(packet) for … -
Django searching for user with url
I have a problem with django. I try to search for users by getting an inputvalue and append this value to my url, so that one can basically search by typing a name in the url too (like it is by Instagram). For example: "localhost/name", it gives me all information to the User. Although the value is in the url and I have a dynamic url function, it doesn´t work. I read a lot of questions here but none worked for me. Thanks in advance. urls.py path("<str:name>/", views.search, name="search"), views.py @login_required(login_url="login") def search(response, name=None): if response.method == "POST": searched = response.POST['searchinput'] users = User.objects.filter(username=name) return render(response, "main/search.html", {"searched":searched, "user":users}) else: return redirect("home") base.html (for the input) <form id="searchform" class="form-inline my-2 my-lg-0" name="searchinputform" method="POST" action=" {% url 'search' name=None %}"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" name="searchinput" id="searchinput" placeholder="Suche" > <script> $( "#searchform" ).submit( function( e ) { e.preventDefault(); document.location = $( "#searchinput" ).val(); } ); </script> -
How to add data from a Postgres View to an existing Django View?
I’m new to Django and still trying to get my head around some of its concepts. So far I have been able to get everything I want working, except for this thing where I clearly don’t fully grasp some of its concepts. If only I knew where the gap in my understanding is. I have a Postgres database with a number of tables. All tables are in models.py and I can read from the main table tbl_items using a Django model and template. So far so good. There is one more complex bit of data that needs to be combined from three tables in two JOINS. I have created a Postgres View that does the heavy lifting with all the JOINS and it works fine. I can query the View from the PSQL command line as if it was a real table and everything works as expected. I then added the Postgres View tbl_combi to models.py, migrated it, and figured that from now on, every part of Django should be oblivious to the fact that tbl_combi is actually a Postgres View instead of a real table. This is the relevant part from models.py: from django.db import models class TblItems(models.Model): item_id … -
Django Formset: how to get the current user? (using django-extra-views)
I'm used to collecting the current logged in user in a CreateView and passing it to the form like so: class MakeFantasyTeam(CreateView): form_class = MakeFantasyTeamForm [...] def form_valid(self, form): form.instance.tourney = Tournament.objects.filter(id=tourney_id).get() form.save() return super(MakeFantasyTeam, self).form_valid(form) However, this doesn't seem to work when using an InlineFormSetView as provided by django-extra-views. I get an error NOT NULL constraint failed: tournament_invite.invited_by_id and I'm not sure how to get the user.id passed on to the form. My View: class InvitePlayersView(InlineFormSetView): template_name = 'invite_players.html' model = Tournament inline_model = Invite form_class = InvitePlayerForm pk_url_kwarg = 'tourney_id' factory_kwargs = {'can_delete': False, 'extra': 1} def formset_valid(self, formset): tourney_id = self.kwargs['tourney_id'] formset.instance.invited_for = Tournament.objects.filter(id=tourney_id).get() formset.instance.invited_by = self.request.user formset.save() return super(InvitePlayersView, self).formset_valid(formset) def get_success_url(self): return reverse('make_team', kwargs={'tourney_id': self.object.invited_for.id}) My Model: class Invite(models.Model): name = models.CharField(max_length=200, blank=True, null=True) email = models.CharField(max_length=320, null=False, blank=False, validators=[EmailValidator],) invited_by = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING) invited_for = models.ForeignKey(Tournament, on_delete=models.DO_NOTHING) created_dt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email def get_absolute_url(self): return reverse('home') My Form: class InvitePlayerForm(forms.ModelForm): class Meta: model = Invite fields = ('name', 'email',) Any tips or hints much appreciated! Thank you, Jon -
my add to cart form throwing me to the register form
i created a add to cart form in my section.html but when i click add to cart button it redirect me to register page what i want to achieve is load the same page and open the same spot where i click add to cart but it not happening here is my section.html <ul class="sec"> {% for section in section_list %} <div class="card col-11" id="{{ section.id }}"> <div class="card-header"> {{ section.title }} </div> <div class="card-body"> <h5 class="card-about">{{ section.about_section }}</h5> <br> <i class="price fas fa-rupee-sign"> {{ section.price }}</i> <br> <br> <i class="icon text-white fas fa-chalkboard-teacher"> {{ section.teacher }}</i> <i class="icon text-white fas fa-clock"> {{ section.content_duration}}</i> <i class="icon text-white fas fa-tags"> {{ section.subject.name }}</i> <form action="/{{section.id}}" method="POST"> {% csrf_token %} <input hidden type="text" name="section" value="{{section.id}}"> <input type="submit" class="btn btn-outline-primary" value="Add To Cart"> </form> </div> </div> {% endfor %} </ul> and here is my views.py for section.html @method_decorator(login_required, name='dispatch') class Sections(View): def post(self, request, subject_id): sections =request.POST.get('section') cart = request.session.get('cart') if cart: cart[sections] = 1 else: cart = {} cart[sections] = 1 request.session['cart'] = cart print(request.session['cart']) return redirect('subjects:section', subject_id=subject_id) def get(self, request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) # retrieve the subject sections = subject.section.all() # get the sections related to the subject return … -
Virtualenv and django not working in bash on windows 10
I have a problem with using virtualenv and django in bash. If I type python -m venv env in cmd, then env\Scripts\activate, and then virtualenv - I get 'virtualenv' is not recognized as an internal or external command, operable program or batch file.. If I do the same in bash I get bash: virtualenv: command not found. How do I fix this? -
How to get total sum based on the date__year?
Here in the template I am iterating MyModel objects. Now in the template I want to get the total sum of integer fields for the particular year. I don't know how I can I use these three functions in order to get the total sum of field? Or there might be any better approach ? model class MyModel(models.Model): date = models.DateField() field1 = models.DecimalField(default=0.0) field2 = models.DecimalField(default=0.0) views def get_total_field1(year): return MyModel.objects.filter(date__year=year).annotate(total=Sum('field1'))['total'] def get_total_field2(year): return MyModel.objects.filter(date__year=year).annotate(total=Sum('field2'))['total'] def get_total(year): return get_total_field1() + get_total_field2() class MyView(ListView): model = MyModel template_name = 'my_template.html' template {% for obj in objs %} <tr> <td>{{obj.date|date:'Y'}}</td> <td>Field 1 total sum for obj.date </td> <td>Field 2 total sum for obj.date</td> <td>Field 1 total + field2 total </td> {% endfor %} -
Update two tables simultaneous when using POST method Django
So, I need your help again. I'm struggling with a little problem and I didn't find any solution for it. I'm having two tables in my models.py and what I want to do is to update both tables status from my models using post method. Can you help me with any ideas? Thank you in advance. My models.py: class Chat(models.Model): chat_id = models.IntegerField(primary_key=True, unique=True, blank=True) payload = models.CharField(max_length=299, validators=[validate]) user_id = models.IntegerField() utc_date = models.DateTimeField(auto_now_add=True, blank=True) status = models.CharField(max_length=10) class ScheduleTable(models.Model): status = models.CharField(max_length=10) views.py: @api_view(['GET', 'POST']) def get_chat(request): if request.method == 'GET': chat_objects = Chat.objects.all() chat_serialize = ChatSerializer(chat_objects, many=True) return JsonResponse(chat_serialize.data, safe=False) elif request.method == 'POST': chat_data = JSONParser().parse(request) chat_data['status'] = 'new' chat_data['chat_id'] += 1 chat_serializer = ChatSerializer(data=chat_data) if chat_serializer.is_valid(): chat_serializer.save() return JsonResponse(chat_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(chat_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django how to add incline css from a deep rooted folder
I've checked all the similar questions and it doesn't exactly target deeper rooted folders and I've also tried their solutions and it hasn't worked. In my HTML i have this: <div class="c-bg-img-center" style="height:800px;background-image: url({% "index/img/content/shop3/21.jpg" %})"> The image I am searching to add to my HTML page is found here: Project\index\static\index\img\content\shop3\21.jpg I've tried different variations of methods that I've found online and no luck - please don't thumbs me down on the verge of being banned from asking anymore questions sigh -
how to get access to the django class object
i have created a model class in django class metaTag(models.Model): page_choice=[ ('index','index'), ('about','about'), ('carrer','carrer'), ('base','base'), ('checkup','checkup'), ('contact','contact'), ('faq','faq'), ('checkup','checkup'), ('app','app'), ('googleads','googleads'), ('graphics','graphics'), ('seo','seo'), ('socialmedia','socialmedia'), ('web','web'), ] page=models.CharField(max_length=15,choices=page_choice,default='index') title=models.CharField(max_length=50,default="AdsOptimiser") description=models.CharField(max_length=160,default="AdsOptimiser") keywords=models.CharField(max_length=200,default="AdsOptimiser") def __str__(self): return self.page what i want to achive by this i want my client have an option to change the title keywords and description meta tags from its admin panel to achive this i created this class so the client can fill the data now i am confused how to plug in the data and what will be the optimal way to do it -
How do i properly show a flash message in django
I have this view function that needs to send a flash message to a user when they sign up. Now that is running well but the problem is that I set an error message to show when the username or password is incorrect and its always showing there by default. Here is my code views.py def signup(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'An account was created for ' + user) return redirect('login') def login_user(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Incorrect Username or Password') And when I go to the login page its just showing me incorrect username or password even though I just got there How can I make it to show only when the username or password is incorrect Thanks for your contribution -
I want to make a staff user by default
I am making a library system with signup pages (admin and user), so when I make an admin user I want to make it in staff, so how can I use (is_staff)? this is my registration function... def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account created successfully') return redirect(loginpage) context = {'form':form} return render(request, 'pages/register.html', context) -
Detail view context
how can i get all images of item into context i tried {% for image in item.images.all %} in template but it doesn't work. i dunno how to filter it , ty for ur answer models class Item(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/', null=True) size = ArrayField(models.CharField(max_length=255)) price = models.PositiveIntegerField() on_sale = models.BooleanField(default=0) discount = models.PositiveIntegerField(null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('single_product', kwargs={'slug': self.slug}) def get_sale(self): price = int(self.price * (100 - self.discount) / 100) return price class ItemImage(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, related_name='images') images = models.ImageField(upload_to='photos/%Y/%m/%d/', null=True) def __str__(self): return self.item.name views class ItemDetail(DetailView): model = Item context_object_name = 'item' template_name = 'essense/single-product-details.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) -
urlpatterns conflict <str:username>/
I have a problem with url paths. As I understand the path users/ is perceived as <str: username>/ named users. Is it possible to solve this problem without creating a new application? urlpatterns=[ path('',PostList.as_view(), name='index'), path('<str:username>/new/',News.as_view(), name='new'), path('<str:username>/', user_posts, name='profile'), path('<str:username>/<int:post_id>/', post_view, name='tak'), path('<str:username>/<int:post_id>/add_comment/', comment_add, name='add_comment'), path('<str:username>/<int:post_id>/edit/', Update.as_view(), name='edit'), path('users/',user_list,name='user_list'), path('users/<str:username>/',user_detail,name='user_detail'), ] -
django-xlwt ['“download” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
i'm trying to export some data from database , i've used xlwt package , my python version is 3.7.0 it seems xlwt doesnt support python 3.7 !?and my django version is 3.2 class Post(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) title= models.CharField(max_length=80) date = models.DateTimeField(auto_now_add=True) my views to download the data def daily_download(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{0}".xls'.format( timezone.datetime.now().strftime('%Y%m%d')) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('vistors') row_num = 0 font_tyle = xlwt.XFStyle() font_tyle.font.bold = True columns = ['user','date','title'] for col_num in range(len(columns)): ws.write(row_num,col_num,columns[col_num],font_tyle) font_tyle = xlwt.XFStyle() rows = Vistor.objects.all().values_list('admin__username','date','title') for row in rows: row_num +=1 for col_num in range(len(row)): ws.write(row_num,col_num,str(row[col_num]),font_tyle) wb.save(response) return response but it raise this error ['“download” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] i also changed file name to a simple string but doesnt work , is there something else i should change please ?! or any other method to achieve it if xlwt expired -
Can Peewee use highlight(), which is SQLite's FTS5 (full text search) auxiliary function?
SQLite's FTS5 supports highlight(). That auxiliary function returns tags for results from full text search queries: see the official documentation. Peewee's code on Github, in the <sqlite_ext.py> module also mentions highlight(), although in passing. Built-in auxiliary functions: bm25(tbl[, weight_0, ... weight_n]) highlight(tbl, col_idx, prefix, suffix) snippet(tbl, col_idx, prefix, suffix, ?, max_tokens) I've found no example code in Peewee's documentation or reference to highlight(), even though Peewee already has support for bm25() and rank() as present FTS5 auxiliary functions. Unless I've missed something, how do I use FTS5 highlight() with Peewee in my Python code? (I'm using Django, if that matters.) -
why are styles not getting applied to Django URLField
I have a model for the profile in it there are different fields like CharField and also URLField but on the page, the styles are getting applied to the input of other fields but are not getting applied to the input of URLField here is my models.py: and here is my forms.py: class ProfileForm(ModelForm): class Meta: model = Profile fields = [ "name", "email", "username", "location", "bio", "short_intro", "profile_image", "social_github", "social_twitter", "social_linkedin", "social_youtube", "social_website", ] def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({"class": "input"}) and here is my HTML: {% extends 'main.html' %} {% block content %} <!-- Main Section --> <main class="formPage my-xl"> <div class="content-box"> <div class="formWrapper"> <a class="backButton" href="{% url 'account' %}"><i class="im im-angle-left"></i></a> <br> <form action="{% url 'edit-account' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input class="btn btn--sub btn--lg my-md" type="submit" value="Submit" /> </form> </div> </div> </main> {% endblock %} and here is an example of gif of what's happening: -
Django Query - Annotate With Boolean Value From Date Comparison
I want to write a query which will have an annotation of expired based on a comparison of a date in the model and the date/time of now and receive a boolean value depending on the outcome. I can't find how this is done. I have tried the below so far: .annotate(expired=F( F('date_updated') > datetime_now)) Can someone let me know the way to achive this? -
How use vanilla JavaScript to add ajax request on Django instead of Jquery
All tutorials cover the implementation of AJAX in Django only using the JQuery library. $.ajax({ url: form.attr("data-validate-username-url"), data: form.serialize(), dataType: 'json', success: function (data) { if (data.is_taken) { alert(data.error_message); } } }); But I want to use the vanilla JavaScript to handle everything, anyway to do that? -
Django-import-export doesn't skip unchanged when skip_unchanged==True
I'm building an app using Django, and I want to import data from an Excel file using django-import-export. When importing data I want to skip unchanged rows, for this, I'm using skip_unchanged = True in the resource class (like below) but I get unexpected behavior. In my model, I have an attribute updated_at which is a DateTimeField with auto_now=True attribute, it takes a new value each time I upload the Excel file even if the values of rows have not changed in the file. Below are portions of my code. models.py class HREmployee(models.Model): code = models.IntegerField() name_en = models.CharField(max_length=55) status = models.CharField(max_length=75) # IH in HR file # other fields to be imported from the file ... # fields that I want to use for some purposes (not imported from the file) comment = models.TextField() updated_at = models.DateTimeField(auto_now=True) resources.py class HREmployeeResource(ModelResource): code = Field(attribute='code', column_name='Employee Code') name_en = Field(attribute='name_en', column_name='Employee Name - English') status = Field(attribute='status', column_name='Employee Status') # other fields to be imported ... class Meta: model = HREmployee import_id_fields = ('code', ) skip_unchanged = True So, can anyone help me to fix this unexpected behavior, please? -
django to find static css files for my HTML page
I'm trying to reach some of my css files but I can't seem to get the directory right. For example I have a link in my home.html: <link href="assets/plugins/revo-slider/css/settings.css" rel="stylesheet" type="text/css"/> I've converted it to: <link href="{% 'assets/plugins/revo-slider/css/settings.css' %}" rel="stylesheet" type="text/css"/> But that's the incorrect directory because I recently moved the file to where it is now as shown below. my folder structure is as follows: project/ ├────── Index/ │ ├──_static/ │ │ ├── css/ (.css files) │ │ ├── js/ (javascript files) │ │ ├── img/ (images files) │ │ ├── media/ (video files) │ │ └── plugins/ (.css plugin files) │ │ │ └── templates/ │ └── index/ │ ├── home.html │ └── about.html ├── manage.py └── project folder with settings.py,url.py my settings.py includes: line 5: BASE_DIR = Path(__file__).resolve().parent.parent line 90: STATICFILES_DIRS = [ "/index/static", ] I've checked the similar questions and youtube tutorials but I've seen some which suggested I add: os.path.join(BASE_DIR, 'static') in line 91 but i've seen conflicting codes through Youtube tutorials, first step is getting the directory right in my html though, if anyone can help it'd be great -
I dont know if i should use models.Foreignkey or just Charfield to store oauth token
I need to store the username and twitter token when he/she logs in and then later use it for whatever purpose, should i use FK for the twiter token field? -
How to filter not only by outerref id in a subquery?
I have a problem with filtering by boolean field in a subquery. For example, I have two models: Good and Order. class Good(models.Model): objects = GoodQuerySet.as_manager() class Order(models.Model): good = models.FK(Good, related_name="orders") is_completed = models.BooleanField(default=False) I want to calculate how many completed orders has each good. I implemented a method in Good's manager: class GoodQuerySet(models.QuerySet): def completed_orders_count(self): subquery = Subquery( Order.objects.filter(good_id=OuterRef("id")) .order_by() .values("good_id") .annotate(c=Count("*")) .values("c") ) return self.annotate(completed_orders_count=Coalesce(subquery, 0)) This method counts all existing orders for a good, but it works when I call it like this: Good.objects.completed_orders_count().first().completed_orders_count To get the correct value of completed orders I tried to add filter is_completed=True. The final version looks like this: class GoodQuerySet(models.QuerySet): def completed_orders_count(self): subquery = Subquery( Order.objects.filter(good_id=OuterRef("id"), is_completed=True) .order_by() .values("good_id") .annotate(c=Count("*")) .values("c") ) return self.annotate(completed_orders_count=Coalesce(subquery, 0)) If I try to call Good.objects.completed_orders_count().first().completed_orders_count I got an error: django.core.exceptions.FieldError: Expression contains mixed types. You must set output_field. -
Ability to find certain pages through search
I want to have a search bar that search all the views that are static and supplies search results for example this page here has the function I need: https://cagenix.com/ . If you click the magnifying glass it opens a search bar and allows you to search all their static pages and supplies the user with results. Is there any way to do this in Django views? -
Django Rest Framework Grouping results by Foreign Key value
I am trying to do a child list model. This model has parent foreign key and child foreign key. What I want to do is to gather the ones with the same parent value under a single group. If the parent 1 has 3 child, the result should look like this: { first_name: "bla bla" last_name: "bla bla" children: [ { first_name: "bla bla"} { first_name: "bla bla"} { first_name: "bla bla"} ] } Is there any way to do this in child list serializer? I just couldn't make it. I want to go to the url address according to the parent value and make a grouping as above. First solution that came to mind is using the related name field. I tried to do this, but I was unsuccessful. I can write similar codes, I have already written for other apps on this project. However, when the subject comes to the list of children, my brain is failing me. I can't find the right thing to do, I can't understand. Models class ChildProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True, verbose_name=AccountStrings.ChildProfileStrings.user_verbose_name, related_name="user_child") city = models.ForeignKey( City, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=AccountStrings.ChildProfileStrings.city_verbose_name, related_name="city_child_profiles") hobbies = models.CharField( max_length=500, null=True, blank=True, verbose_name=AccountStrings.ChildProfileStrings.hobbies_verbose_name) class ParentProfile(models.Model): …