Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect to detail page after authentication
here is my code class UserProfileView(DetailView): template_name = 'main/userprofile.html' context_object_name = 'userprofile' model = ProfilePersonal # def dispatch(self, request, *args, **kwargs): # if request.user.is_authenticated: # pass # else: # return redirect('/accounts/login/?next=userprofile/6') # return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) comments_connected = Review.objects.filter(profile=self.get_object()).order_by('-date_created') context["comments"] = comments_connected context['comment_form'] = ReviewForm return context def post(self, request, *args, **kwargs): if request.user.is_authenticated: new_comment = Review(content=request.POST.get('content'), rating=request.POST.get('rate'), profile=self.get_object(), user = self.request.user) else: return redirect(f'/accounts/login next=userprofile/{self.get_object()}') new_comment.save() return self.get(self, request, *args, **kwargs) Everything works fine except for the fact that if a user try to drop a comment and the user is not login in he will be be redirected to the login page but after authentication i want to redirect the user the user detail page where he was redirected from. for example if i was redirected from 127.0.0.1:8000/userprofile/6 after logging in i should be redirected to 127.0.0.1:8000/userprofile/6 in order to continue with what i was doing -
Django & Cassandra: How to give choice field to a model with Django Cassandra engine?
Hey guys I am new to Cassandra and was trying to integrate it with Django with Django Cassandra engine package. I have a choice field with some types like, TYPE = [('1', '1'), ('2', '2'), ('3', '3'),] with postgres, I can use a CharField with choices, but how can I achieve the same with Cassandra? Can anyone provide some hints? Thanks in advance. -
How to retrieve foreign field name in Django Rest Framework
I have 2 models one for a user and another for associated files for the user Models.py class IndividualUser(models.Model): membership_id = models.CharField(primary_key=True, max_length=100, default=1) profile_image = models.ImageField(blank=True, upload_to ="individual_member_profile/", null=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) class MemberCatalogue(models.Model): membership_id = models.ForeignKey(IndividualUser, default=None,on_delete=models.CASCADE, related_name="member_catalogue") files = models.FileField(upload_to="individualmembercatalogue/") Currently Iam getting absolute path for files. I need a filename uploaded by user for which Iam trying to get "files" field and and then split it with "/". But Iam struggling to get the files field from MemberCatalogue. My serializers look like this at the moment: class MemberCatalogueSerializer(serializers.ModelSerializer): files = serializers.FileField() class Meta: model = MemberCatalogue fields = ['id','membership_id', 'files'] class IndividualMembersSerializer(serializers.ModelSerializer): member_catalogue = MemberCatalogueSerializer(many=True) filename = serializers.SerializerMethodField('get_filename') def get_filename(self, obj): return obj.individualmember.files class Meta: model = IndividualMembers fields = "__all__" But I cant get the desired output. Expected output is like { "membership_id": "142369ca1b1484d8d9d6d87fdc8543db", "member_catalogue": [ { "id": 156, "membership_id": "142369ca1b1484d8d9d6d87fdc8543db", "files": "http://127.0.0.1:8000/individualmembercatalogue/some_file.pdf" "filename" : "some_file.pdf" } ], "profile_image": null, "firstname": "John", "lastname": "Doe", } -
File download in Django template
I am trying to download a file, but getting the download in html format, how I can get the file in its on format class Certificate(models.Model): name = models.CharField(max_length=80, blank=True, null=True) cert = models.FileField(upload_to='cert/', blank=True, null=True) def download_link(self): self.cert.url <a href="{{ obj.download_link }}" download> Download File</a> Tried the following way also but still in html format def download_link(self): path = self.cert.path filename = 'download.extension' fl = open(path, 'r') mime_type, _ = mimetypes.guess_type(path) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response -
how to test a unit test using pytest django if there is a function defined but not the class?
@api_view(['GET']) def get_search(request): search_text = get_searchText() return Reponse({"search-txt":search_text}) here, search_txt is an api for searching the text,and search_text is a variable I tried below but was unable to test the above code, from django.test import TestCase, Client class TestViews(TestCase): def setUp(self): self.client = Client() self.searchtxt_url = reverse('search-txt') def test_search_project(self): response.self.client.get(self.searchtxt_url) self.assertEquals(response.status_code, 200) what can be a possible way to test a function with api -
Django large queryset return as response efficiently
I have a model in django called "Sample" I want to query and return a large number of rows ~ 100k based on filters. However, it's taking up to 4-5 seconds to return the response and I was wondering whether I could make it faster. My current code looks like this: @api_view(['POST']) def retrieve_signal_asset_weight_ts_by_signal(request): #code to get item.id here based on request qs = Sample.objects.filter( data_date__range=[start_date, end_date], item__id = item.id).values(*columns_required) df = pd.DataFrame(list(qs), columns=columns_required) response = df .to_json(orient='records') return Response(response, status=status.HTTP_200_OK) Based on multiple test cases -- I've noticed that the slow part isn't actually getting the data from DB, it's converting it to a DataFrame and then returning as JSON. It's actually taking about 2 seconds just for this part df = pd.DataFrame(list(qs), columns=columns_required). Im looking for a faster way to convert queryset to a json which I can send as part of my "response" object! Based on this link I've tried other methods including django-pandas and using .values_list() but they seem to be slower than this, and I noticed many of the answers are quite old so I was wondering whether Django 3 has anything to make it faster. Thanks Django version : 3.2.6 -
I want user can change website language using drop-down without login but if they log in website should translate in their saved language preference
I am using a Django website in which a user can change their language using a drop-down menu. I use Django i18n for the translation of the website. Now problem is that I want a user can visit some pages of the website without login and they can change the language using a drop-down. But when a user logs in, the language of the website should change to the default language of that user's we store in their porifle section. How can I achieve this? language_form.html {% load i18n %} <form action="/i18n/setlang/?next={% url 'homepage' %}" method="post"> {% csrf_token %} <select name="language" style="padding: 4px 3px;"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_current_language_bidi as LANGUAGE_BIDI %} {% for language in LANGUAGES %} <option value="{{ language.0 }}"{% if language.0 == LANGUAGE_CODE %} selected {% endif %} "> {{ language.1 }} </option> {% endfor %} </select> {% for lang in aLANGUAGES %} {{lang.list}} {% endfor %} <input type="submit" value="Change language" style="padding: 3px 3px; margin-right: 10px;"> </form> The above code is my drop-down form for the select languages but I want user can select their preferred language in the profile section and that will be enabled automatically when they logged … -
How to correctly render a Multiplechoice ModelForm in Django
So I have two models, one to store categories and their related color and another one to store the categories selected by a user like so: # Models class Category(models.Model): poller_category = models.CharField(max_length=30) category_color = models.CharField(max_length=15) class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.CharField(max_length=2000) I now want to render out a MultipleSelectWidget so that the user can select categories to use as a filter. # Form class SelectCategoryForm(forms.ModelForm): choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Category exclude = ["poller_category", "category_color"] How can I now render all of the categories and their associated color in the template? My below loop doesn't render any (Note: the form is passed to the context, if I use {{ select_form }} it renders the default one) # Template <!-- Filter form --> <div class="filter-form-wrapper"> <form method="post" action="."> {% csrf_token %} <div id="form-wrapper"> <ul> {% for item in filter_form %} <li style="color: {{ item.category_color }}">{{ item.poller_category }}</li> {% endfor %} </ul> <button class="save-button" type="submit">Save</button> </div> </form> </div> -
Django - Facebook ads (panel and targeted ads)
I would like to setup my web application so that users (businesses or other type of account) can run ads for the users (normal users) as Facebook based on user's interests, what approach should I take? Thanks! -
Django test parallel with 1 DB
I am trying to run my tests in parallel using manage.py test --parallel. By default this will use a different DB for each thread. Each process gets its own database Is it possible to only use one? Also is it a bad practice and why? -
How to loop in excel row with xlwt and django?
Here I am trying to export some report of customers in the excel format using xlwt. While exporting I am getting issue while rendering related products of customer. The current response I am getting is: The response I want is : response = HttpResponse(content_type="application/ms-excel") response["Content-Disposition"] = 'attachment; filename="report_detail.xls"' wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet(f"Report Detail", cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = [ "Customer ID", "Products"] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) rows = [] for obj in qs: rows.append(obj.customer_id) prods = [(p.name, p.code) for p in obj.products.all()] rows.append(", ".join(map(str, prods))) for i, e in enumerate(rows, start=2): ws.write(int(i / 2), int(i) % 2, e) wb.save(response) return response -
Setting up a Test environment
I have currently dockerised my django+springboot application(development) and deployed in a remote server(Digital ocean). For testing purposes, I have cloned the applications and deployed at different ports. But the functionalities working in development server are getting reflected in Test server. Would like to know the general practice in cloning a development server for a test server -
How to lock the default choice without giving any options in DJANGO
I've been working with a model with has one the field as a choice field and multiple choices are provided. For eg-> The gender field is a choice field where users can choose from a drop down menu. But in a certain case, I only want the form to be open to female candidates, so the choices won't be shown, and the field will automatically be set as 'female' in the backend. How can I do this? Here are the code snippets from my code -> // models.py class RegisterUser(models.Model): GENDER_CHOICES= ( ( constants.MALE, constants.MALE_STR, ), (constants.FEMALE, constants.FEMALE_STR), ( constants.OTHERS, constants.OTHERS_STR, ), ) name = models.CharField(max_length=100) age = models.IntegerField(blank=True, null=True) college = models.CharField(max_length=100) gender = models.PositiveSmallIntegerField( choices=GENDER_CHOICES, default=constants.MALE ) // form.py class RegsiterForm(forms.Form): gender = forms.ChoiceField( label="Select Gender (default is Male)", widget=forms.Select( attrs={"class": "form-control", "placeholder": "Select Gender"} ), choices=GENDER_CHOICES, ) // views.py @login_required def publish_app_without_apk(request, **kwargs): template_name = "registerform.html" context = {} if request.method == "POST": form = form_class(request.POST) if form.is_valid(): name = form.cleaned_data.get("name") age = request.POST.get("age") college = request.POST.get("college") gender = request.POST.get("gender") -
What is the Best Way To Sync Multiple Database Table To Online Database using rest api
I have a software which store data in local sql server in multiple tables Want To give sync button and call api and transfer the data from local to live Software are install in multiple systems so it can happen data can transfer at same time what techniques i can use . So Server will not lack -
Django - Heroku - debug error 500 when deleting an object in Prod
Problem: Server Error 500 when trying to delete a user account in Prod. Scenarios: Delete a user account in Dev - works fine Create a user account in Prod - works fine Delete a user account in Prod - error 500 view.py: @login_required def account_destroy_view(request, id=None, *args, **kwargs): try: obj = request.user except request.user.DoesNotExist: raise Http404 if request.method == "POST": try: customer = StripeRecord.objects.get(user_id=obj.id) stripe.api_key = config('STRIPE_API_KEY') stripe.Customer.delete(customer.stripe_customer_id) except StripeRecord.DoesNotExist: pass obj.delete() return redirect("/") return render(request, "accounts/delete.html", {"object": obj}) accounts model.py: class User(AbstractUser): date_time = models.DateTimeField(default=datetime.datetime.now()) stripe model.py: User = settings.AUTH_USER_MODEL class StripeRecord(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) ... Heroku log: Sep 23 19:37:37 weatherapp app/web.1 10.1.24.136 - - [24/Sep/2021:02:37:36 +0000] "POST /delete/ HTTP/1.1" 500 145 "https://www.weatherapp.com/delete/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52" What I've tried & questions: I've checked Stripe logs, the object has been deleted on Stripe. So the issue isn't on the Stripe env var or integration. Tried to delete a user account directly using Django admin tool in Prod - still error 500. I suspect it's because I created the model with AbstractUser and it is a foreignkey to another model? How to get more details on the … -
HTML inserting extra characters into URL
I'm creating an ebay style website that auctions off items. I have a form that takes in the values for the listing required by the model. The form renders well but when I submit the form I get the error: <class 'TypeError'> views.py 80 ("l = Listing(title=title, description=description, url=url, user=user_id, category=category)") forms.py class NewListingForm(forms.Form): title = forms.CharField(max_length=200) description = forms.CharField(max_length=500) url = forms.URLField() bid = forms.DecimalField(decimal_places=2, max_digits=10) category = forms.ModelChoiceField(queryset=Category.objects.all()) views.py ** added around line that's throwing the error def newListing(request): try: if request.method == "POST": newListingForm = NewListingForm(request.POST) if newListingForm.is_valid(): title = newListingForm.cleaned_data['title'] description = newListingForm.cleaned_data['description'] url = newListingForm.cleaned_data['url'] bid = newListingForm.cleaned_data['bid'] category = newListingForm.cleaned_data['category'] current_user = request.user user_id = current_user.id **l = Listing(title=title, description=description, url=url, user=user_id, category=category)** l.save() b = Bid(price=bid, bid_count=0) b.listing.add(l) b.save() return HttpResponseRedirect(reverse("index")) else: newListingForm = NewListingForm() return render(request, "auctions/newListing.html", { 'form': newListingForm }) except Exception as exc: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) newListingForm = NewListingForm() return render(request, 'auctions/newListing.html', { 'form': newListingForm }) models.py class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() user = models.ForeignKey('User', on_delete=models.CASCADE, name='author') category = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="") def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = … -
How to do three functions by one submit button with only one form document?
I'm having a problem to call multiple functions on one click submit button. I have one form which user need to attach one file (exls document), and I need one document to use for 3 functions. I need to save document, do some pandas stuff and I need to show it in html. Can I do this by putting it in class or something? I really need help for this, thanks in advance. def save_exls(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() return redirect('html_exls') else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form,} return render(request, 'list.html', context) def pandas_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #pandas stuff done.to_excel(writer, sheet_name=name) output.seek(0) response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) def html_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #pandas stuff for … -
Use a queryset to display two filtered data in django?
I have a table Documents and it has a field named type and the type has two data's namely - type1 & type2 Now my requirements is - i have a bootstrap tabs type1 & type2, and i need to display data accordingly on the template Which is efficient way to do this ? Using two variables data = Documents.objects.filter(id=pk) type1 = data.filter(type="type1") type2 = data.filter(type="type2") and then pass it to context context = { "type1":type1,"type2":type2 } Is there any other best way to do this ? -
How to add an event with JavaScript when a button is clicked
I've uploaded a similar question in a previous post, but I'm re-posting because what I'm trying to achieve is a little clearer. We are outputting the list of students as a table. If we check the checkbox and click the Add Teacher button, we want the name of the currently logged in teacher to be added to the teacher field of the selected row. You can get the name of the currently logged in account with {{request.user.name}} . And I want it to be saved in DB by sending it to the server. <table class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td>{{ student.techer }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Techer" class="addtecher"> urls.py path('student/<int:id>/edit/', views.edit_student, name='edit_student') views.py def edit_student(request, id): student = get_object_or_404(Student, pk=id) edited_student, errors = Student.student_form_validation(request) if errors: return JsonResponse({'code': 'error', 'error': errors}) student.name= edited_student.name student.age = edited_student.age student.register_date … -
Django queryset group by and count for related fields
I have this models with this relations class Product(models.Model): code = models.CharField( _("Code"), max_length=50, unique=True ) name = models.CharField( _("Name"), max_length=150 ) class ProductOption(models.Model): product = models.ForeignKey(Product, verbose_name=_("Product"), on_delete=models.CASCADE, related_name='options') vtype = models.CharField(_("Type"), max_length=50) text = models.CharField(_("Text"), max_length=50) With this example data prod1 = Product(code='1', name='Name 1') ProductOption(product=prod1, vtype='Color', text='Blue') ProductOption(product=prod1, vtype='Size', text='M') ProductOption(product=prod1, vtype='Material', text='Cotton') prod2 = Product(code='2', name='Name 2') ProductOption(product=prod2, vtype='Color', text='Red') ProductOption(product=prod2, vtype='Size', text='X') ProductOption(product=prod2, vtype='Material', text='Cotton') prod3 = Product(code='3', name='Name 3') ProductOption(product=prod3, vtype='Color', text='Red') ProductOption(product=prod3, vtype='Size', text='L') ProductOption(product=prod3, vtype='Material', text='Cotton') How can I build a query with the ORM with this result [ {'vtype': 'Color', 'text': 'Blue', 'count': 1}, {'vtype': 'Color', 'text': 'Red', 'count': 2}, {'vtype': 'Size', 'text': 'M', 'count': 1}, {'vtype': 'Size', 'text': 'X', 'count': 1}, {'vtype': 'Size', 'text': 'L', 'count': 1}, {'vtype': 'Material', 'text': 'Cotton', 'count': 3}, ] I test a lot of options like using Concat, and Count but I fail. -
Upload contacts from my phone into a Django app
I am creating a django app and one of the functionalities I would like to add is that, if I want, I can upload into my app contacts that I have on my iphone. Basically the flow I would like to create is that if a user lands on the page on it's mobile phone and click on "upload", the app opens the user's contact list and the use can select the contact or contacts he would like to upload. How can I do it? -
How to connect Django Api with iOS (Swift) app?
I have tried researching how to connect my Django API in my ios swift app. My goal is to create a web app and an ios app in order to do it I have created an API with Django but I'm totally new to ios development and I'm trying to connect and authenticate users with my API, I'm trying to use Alamofire in swift. Any books or references ? or examples of functions, Thanks a million. -
DRF Sum values in a JSONFIELD field
I need to return totals from a table (Mysql), but one of the fields is JSONFIELD, with the key value to be added. Testing as below I get the following error: the JSON object must be str, bytes or bytearray, not float JSONFIELD { "repasse_descontos": [ { "nome": "Taxa Administrativa 1º Aluguel", "valor": 175 }, { "nome": "pintura", "valor": 200 } ] } VIEWSET def get_queryset(self): _qs = (Alugueis.objects .filter(ver='s') .values('proprietario') .annotate( total_vcto = Sum('vcto_valor'), total_pagto = Sum('pagto_valor'), total_repasse = Sum('repasse_pagto_valor'), total_descontos = Sum('repasse_descontos__valor') ) .order_by('proprietario') ) return _qs -
How to prevent query >>> on table being loaded? Django Table
I have the current code in my django app to populate a Table with data from a postgres db. It is populating correctly with the following code but seems to be putting > for each item from the table above like a query. Any assistance to get this resolved would be greatly appreciated. Here is the image as well Screenshot of table being displayed with >>>> Thank you in advance for any assistance to get this resolved. All other parts of the DTL is working as designed. <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Call Time</th> <th>Reservation Number</th> <th>Stage Name</th> <th>Update Call</th> </tr> </thead> {% for Call_Note in object_list %} <tr> <th>{{ Call_Note.id }}</th>> <td>{{ Call_Note.call_time }}</td> <td>{{ Call_Note.reservation_number }}</td> <td>{{ Call_Note.stage_name }}</td> <td><a href="/calls/{{ Call_Note.id }}">Modify Call</a></td> </tr> {% endfor %} </tbody> </table> -
django import excel file with multi sheets
hello everyone please I have a concern for using Django’s Tablib module to load an excel file that contains multiple sheets. I don’t know how to retrieve a specific sheet