Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translating Django site into multiple languages?
I have a a Django site with 10-15 models/tables. Each row needs to be translated into at least 4 or 5 languages. What is the most efficient way of implementing localization? I've read you can use .po files. But one would have to mark every single single that needs to be translated, which seems tedious. There are modules that create additional fields for additional languages. This seems to blown up the DB unreasonably. -
Django, ModelChoiceField() and initial value with formset not working
I have the form below in my forms.py. I am setting the self.fields['start'] to ModelChoiceField with queryset=Flow.objects.all(). class GroupForm(ModelForm): class meta: model = Group fields=['conditionn', 'start'] def __init__(self, *args, **kwargs): super(GroupForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.fields['condition'] = forms.CharField(label='Post Condition', widget=forms.TextInput( attrs={'placeholder': 'The system displays the "Home" button'})) #to check what is in the initial initial = kwargs.get('initial', {}) print("wow",initial) self.fields['start'] = forms.ModelChoiceField(label='Success or Abort', widget=forms.Select, queryset=Flow.objects.all()) GroupInlineFormSet = inlineformset_factory(ParentModel, BoundedFlowGroup, form=BoundedFlowGroupForm) In my views, I have class UpdateGroup(Updateview): ... def get_context_data(self, **kwargs): print(self.object) context = super(UseCaseUpdateView, self).get_context_data(**kwargs) if self.request.POST: .... else: context['Another_form'] = AnotherFormSet(instance=self.object, prefix='group') groupQuerySet=context['Another_form'].instance.group_set.all() flowQuerySet=basicGroupQuerySet[0].flow_set.all() context['boundedGroupNested_form'] = BoundedGroupNestedFormSet(initial=[{'start':flowQuerySet}], instance=self.object, prefix='boundedFlowGroup') return context .... Now, in the view, I am trying to set the start initial values with initial=[{'start':flowQuerySet}]. When I print out the flowQuerySet I got the correct values I would need for the start field. However, when I view my render template, I am see all the instances of Flow instead of the ones from the flowQuerySet. So, If the are 1,2,3,4,5,6 Flows and flowQuerySet has only 5, 2,1 - I want only 5,2,1 as selection option in the ModelChoiceField of start, but I am still getting 1,2,3,4,5,6. How do I set the model's instances for … -
Getting complete and exact definition of a Django model attribute
Suppose that I have User model as this: class User(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40, blank=True, null=True) password = models.CharField(min_lengj) connections = models.DecimalField(max_digits=3, default=0, blank=False) ... (other attributes) For a special use case I need to know the exact definition of its fields so I can get definition of connections as a DecimalField with max_digits equal to 3 and default equal to 0 and cannot be blank. How I can acheieve this? -
Django templates won't load but HttpResponse will (repost)
I recently began learning django and have been running into some trouble and I can't figure out why. My problem is quite simple: whenever I try to run my homepage with a template, it throws up a 404 error. My file hierarchy is as such: crm accounts templates accounts dashboard.html urls.py views.py crm urls.py In crm/urls, I have from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')) Then in accounts/urls, there is, from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] And in views, I have from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'accounts/dashboard.html') My dashboard.html is just a basic html file with a title and h1, that's it. Also, whenever I change return render(request, 'dashboard.html') to return HttpResponse('home') in my home function, it decides to show. I have tried recreating the project, uninstalling and reinstalling django, renaming a few things, but none of them seemed to work. -
Django admin: Replicating InLine data when using "Save as New"
I have 2 models: class Series(models.Model): puzzles = models.ManyToManyField(Puzzle, through='SeriesElement', related_name='series') class SeriesElement(models.Model): puzzle = models.ForeignKey(Puzzle, on_delete=models.CASCADE, verbose_name='Puzzle', ) series = models.ForeignKey(Series, on_delete=models.CASCADE, verbose_name='Series', ) puzzle_index = models.PositiveIntegerField(verbose_name='Order', default=0, editable=True, ) class Meta: unique_together = ['puzzle', 'series', 'puzzle_index'] ordering=['puzzle_index'] and the admin Page of Series displays an inline of SeriesElement. class SeriesAdmin(admin.ModelAdmin): save_as = True inlines = (SeriesElementInline,) When I am clicking "save as new", then an error occur going through the net, I gathered that I need to override save_formset, and the following approach seems to be almost working: def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) pdb.set_trace() # for debug for i in instances: if hasattr(i, 'puzzle_id') and not i.puzzle_id: i.puzzle_id = request.puzzle_id # not working i.puzzle_index= request.puzzle_index # not working i.save() formset.save_m2m() super(SeriesAdmin, self).save_formset(request, form, formset, change) However I am not able to figure out how I could recover the original puzzle_id and puzzle_index to be able to re-create SeriesElements that refer to the new series in the code, what should I put instead of request.puzzle_id and request.puzzle_index to retrieve the original values? PS: here is the content of request.POST where all elements seem to be accessible, but I don't know how to get them properly: … -
How do you not create an object when creating a User in Django?
I have a Client model with an User ForeignKey. So, whenever I create a Client I also create an User. This is the Client model: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") city = models.CharField(max_length=200, verbose_name="Cidade") postal = models.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], verbose_name="Código Postal") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Client.objects.create(user=instance) instance.client.save() And this is the view: @login_required(login_url='./accounts/login/') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() # this creates the user with first_name, email and last_name as well! group = Group.objects.get(name='Clients') user.groups.add(group) user.refresh_from_db() # load the profile instance created by the signal user.client.address = form.cleaned_data.get('address') user.client.city = form.cleaned_data.get('city') user.client.postal = form.cleaned_data.get('postal') user.client.nif = form.cleaned_data.get('nif') user.client.mobile = form.cleaned_data.get('mobile') return redirect('client') else: form = SignUpForm() return render(request, 'backend/new_client.html', {'form': form}) And this the form: class SignUpForm(UserCreationForm): address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Av. da Liberdade, 170',})) nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Deve conter 9 dígitos',})) mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Deve conter 9 dígitos',})) city = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Lisboa',})) postal = forms.CharField(max_length=8, … -
Django database structure change to allow multiselect
I am working on a project that requires some database structure changes to allow the users to select multiple values at once. My current structure consists of a chained model relationship as follow: class Service_Specific(models.Model): title = models.CharField(max_length=100, help_text="title of service specific") category = models.ForeignKey(Service_Category, on_delete=models.CASCADE, null=True, help_text="Id of service category") group = models.ForeignKey(Service_Group, on_delete=models.CASCADE, null=True, help_text="Id of service group") type = models.ForeignKey(Service_Type, on_delete=models.CASCADE, null=True, help_text="Id of service type") variant = models.ForeignKey(Service_Variant, on_delete=models.CASCADE, null=True, blank=True, help_text="Id of service variant") tags = TaggableManager(blank=True) def __str__(self): return '%s / %s / %s / %s' %(self.group, self.type, self.variant, self.title) def save(self, *args, **kwargs): self.category = self.variant.category self.group = self.variant.group self.type = self.variant.type return super(Service_Specific, self).save(*args, **kwargs) For now, this model is used to add services to a user who is a Service Provider and it's working fine. ( 1 service at a time ) example (service_variant = "guitar lessons" -> service_specific = "electric guitar" ) The issue is that users tend to offer multiple services related to the same service_variant and they got annoyed because they can not select them all at once. Can somebody help me find the right strategy ?? Thank you. here is my provider service model: class ProviderService(models.Model): provider … -
how can i insert dynamic fields of a form in django into database
i have a form with checkbox inputs the number of inputs is dynamic because i get it from the database,in my form i might have 2 or 3 or N .. checkbox.then from these input the user will check some or all of them and then he click the submit button the problem is that only one input is saved into database and how can i insert it all. can any one help me please i hope the problem is clear.this is my code for the form : ` <form method="post" action="createQcm"> {% csrf_token %} {% for mati in quest %} <INPUT type="checkbox" value ="{{mati.id_question }}" name="choix" > {{mati.questionA }}</input></br></br> {% endfor %} <input type="hidden" name="s" value="{{idQ}}" readonly> ` the view: ` def createQcm(request): q=request.POST["choix"] r=request.POST["s"] rep = contenir(idQuestion=q,idQuiz=r) rep.save() return render(request,'myblog/subject.html') ` -
Django - Checking if user has logged in before
when a user signs up, they get redirected to the homepage. If it is their first time logging in, I want to display a div, however if it is not their first time, I do not want this div to appear. Currently, I am relying on date_joined andlast_login to do this check. However this only checks dates and not the time. Therefore the div will still appear until the date has changed. I only want the div displayed once. This is when the user first logs in. Here is my code so far: views.py: def home(request): context={} user = request.user if user.last_login.date() == user.date_joined.date(): context['isFirstTime'] = 'isFirstTime' else: pass return render(request, 'home.html', context) template: {% if isFirstTime %} <div style="width: 300px; height: 300px; background-color: green;"> </div> {% endif %} Does anybody know how I can alter this so it works with the current time and not the current date. This way the div is only displayed when a user first logs in. Anybody know a solution? Thank you. Also date_joined and last_login are datetime objects stored in the database. -
Django matching a url with paramater to start
In Django 3 I've got a site I'm working on where I need to match a paramater at the start of the url. So test.com/the-data-slug What is odd is I can't figure out why the following code dosen't work. It dosen't match at all. path('<slug:data-slug>/', DataLandingView.as_view(), name="data_landing") I did get the following to work, but I know path is prefered over re_path. re_path(r'^(?P<data-slug>\w+)/$', DataLandingView.as_view(), name="data_landing") I'm really curious what I'm doing wrong with the path call, or is this just something path can't do? -
DRF get only the first serialized instance for list view?
I'm working on a real estate app and want the listings to show only the first image of the Listing. Currently it is showing all images. class Image(models.Model): photo = models.ImageField(blank=True, upload_to=get_image_filename) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) class ImageSerializerForListingList(serializers.ModelSerializer): photo = serializers.ImageField() class Meta: model = Image fields = ('photo', ) class ListingListSerializer(serializers.HyperlinkedModelSerializer): image = ImageSerializerForListingList(many=True, required=False, source='image_set') class Meta: model = Listing fields = ('url', 'address', 'image', ) def get_first_image(self, obj): image = obj.image_set.all().first() return ImageSerializerForListingList(image, many=True).data This is still showing all images, Any advice on this? -
Unable to connect Django Rest framework application with GCP cloud SQL
I created a could SQL instance on GCP for MySql 5.7. I am trying to connect it with Django Rest framework application. I am also using Docker to containerize Django application. I am running Django application on localhost but for MySql I want to use GCP cloud Sql. I got the public IP address of the cloud Sql instance once it was up and running. Then I created a database eitan_database with user jeet and password root. In Django project's settings.py file I updated the database settings as following - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'eitan_database', 'USER': 'jeet', 'PASSWORD': 'root', 'HOST': '35.239.xxx.x', 'PORT': 3306, } } I have used public IP for HOST and for PORT Mysql default 3306. I don't understand what is wrong with the database configuration but when I run server I get the following error. Traceback (most recent call last): eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection eitan-application_1 | self.connect() eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner eitan-application_1 | return func(*args, **kwargs) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect eitan-application_1 | self.connection = self.get_new_connection(conn_params) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner eitan-application_1 | return func(*args, **kwargs) eitan-application_1 | File … -
Download button with function, react
I am using Django and react to make a website. I want to be able to download a websitepost, locally on my computer as a website user. <button className={styles.button} onClick={() => {}}> </button>` How do i finish this button? And what functionality am I missing? -
Accessing localhost not possible on MacOS
my situation is that the website I'm building has a landing page the main App page and the API section. They are respectively reachable with [domain_name], app.[domain_name] and api.[domain_name]. When calling those I don't have any problems reaching them in any browser. When I host them however in my local environment then api.localhost does only work when I call it with Postman. When I try to ping the api.localhost it only says: ping: cannot resolve api.localhost: Unknown host On other systems, this will get a response. In terms of Django Cors stuff, it all seems to be managed correctly as it is working on other systems. But I can add any code if asked for such, just don't want to add everything that I can think of from the Django project. I have no idea what to try or what to change so any help would be beneficial. -
How can form fields be rendered manually in django-bootstrap-datepicker-plus
I have django-bootstrap-datepicker-plus set up in my app. Upon completion, I noticed that my form fields are stacked on rows screenshot whereas I would love to manually render some of the fields on the same row. Although I know the reason for that is because the form is rendered using {% bootstrap_form form %} Here is my rendered template code snippet below. {% extends 'accounts/no_header_footer.html' %} {% block content %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {{ form.media }} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script> <div class="profile-create-form-container"> <form class="profile-create-form" data-certificates-url="{% url 'ajax_load_certificates' %}" data-grades-url="{% url 'ajax_load_grades' %}" data-relationships-url="{% url 'ajax_load_relationships' %}" data-states-url="{% url 'ajax_load_states' %}" enctype="multipart/form-data" id="ProfileCreateForm" method="POST" runat="server"> {% csrf_token %} <fieldset class="form-group text-center"> <span class="navbar-brand"> <img alt="..." height="40px" src="..." width="40px"> Basic Information </span> </fieldset> {% bootstrap_form form %} <div class="container"> <div class="text-center"> <button class="btn btn-dark" type="submit"> <i class="fa fa-save"></i> Save and Continue </button> </div> </div> </form> </div> The question I have is, is it possible to render each form field manually? -
Cannot get Foreignkey Model to Save to Sqlite Database with Django
I have looked over every article on everything that has ever been posted and none of the resolutions seem to fix my issues. I can't seem to get input from my view to save to my database. Theoretically the user will input a contact and business and the contact will associate with the business and the contact will be added however I am like 99% sure I am wrong somewhere, I am just 100% sure I don't know where: Models from django.db import models class Business(models.Model): business_name = models.CharField(max_length=30, unique=True) date_created = models.DateField(auto_now=True) def __str__(self): return self.business_name class Contact(models.Model): name = models.CharField(max_length=30) title = models.CharField(max_length=30) number = models.CharField(max_length=13) email = models.EmailField() business = models.ForeignKey(Business, on_delete=models.CASCADE) def __str__(self): return "%s - %s" % (self.name, self.business) Forms from django import forms from .models import Contact, Business class ContactForm(forms.ModelForm): def __init__(self, business, *args, **kwargs ): super(ContactForm, self).__init__(business, *args, **kwargs) self.fields['business'].queryset = forms.ModelMultipleChoiceField(queryset=business) class Meta: model = Contact fields = ['name', 'title', 'number', 'email', 'business'] class BusinessForm(forms.ModelForm): class Meta: model = Business fields = ['business_name'] Views def add_contact(request): all_contacts = Contact.objects.all if request.method == "POST": business = get_object_or_404(Business, business_name=request.POST['business']) form = ContactForm(request.POST, instance=business) # print(form) if form.is_valid(): new_form = form.save(commit=False) new_form.business = form.business print(new_form) … -
ValueError at /admin/listings/listing/add/
Invalid format string Request Method: POST Request URL: http://localhost:8000/admin/listings/listing/add/ Django Version: 3.0.4 Exception Type: ValueError Exception Value: Invalid format string Exception Location: C:\Users\Ayesha Siddiqha\btre_project\venv\lib\site-packages\django\db\models\fields\files.py in generate_filename, line 305 Python Executable: C:\Users\Ayesha Siddiqha\btre_project\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Ayesha Siddiqha\btre_project', 'C:\Users\Ayesha ' 'Siddiqha\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\Ayesha ' 'Siddiqha\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\Ayesha ' 'Siddiqha\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\Ayesha Siddiqha\AppData\Local\Programs\Python\Python38-32', 'C:\Users\Ayesha Siddiqha\btre_project\venv', 'C:\Users\Ayesha Siddiqha\btre_project\venv\lib\site-packages'] -
Unable to host django on IIS using Fast CGI (wfastcgi). Getting 500 error in browser
I am unable to host a basic django project in IIS. I have been breaking my head over 2 days now and help would be greeeaaatly appreciated :). I have enabled IIS, CGI, and others under the Application Development in IIS. This is my folder structure after creating a simple django project via the below command: django-admin startproject dijky Folder structure: + C:\inetpub\wwwroot + dijky + dijky - __init__.py - settings.py - urls.py - wsgi.py - manage.py - web.config - wfastcgi.py I have copied the wfastcgi.py file into my project folder. I have then Added a website named "dijky" with the below settings Under the Machine name in IIS, Clicked on FastCGI Settings, and have given the Full path and Arguments as so: Then gave the environment variables as: I even tried setting the WSGI_HANDLER to dijky.wsgi.application, since the file C:\inetpub\wwwroot\dijky\dijky\wsgi.py has: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dijky.settings") application = get_wsgi_application() Both don't work My web.config XML file is: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="djangoappiis" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Users\xxxxxxx\Anaconda3\envs\djangy\python.exe|C:\inetpub\wwwroot\dijky\wfastcgi.py" resourceType="Unspecified" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\dijky" /> <add key="DJANGO_SETTINGS_MODULE" value="dijky.settings" /> </appSettings> </configuration> After Starting the server … -
Create a field with grouped attributes from the model in DRF
I want to group a specific attributes from a model instead of serializing them individually more or less like this class MyModel(models.Model): attr1 = models.IntegerField() attr2 = models.IntegerField() attr3 = models.CharField() and serialize will output this { # other attrs "grouped_attrs" : {"attr1": 23, "attr2": 848, "attr3": "foo"} # other attrs } -
Server Connection Refused - Django/Postgresql
I want to preface that everything works on my other computer but with the new macbook I got, I am trying to determine the cause of the issue. The issue is when attempting to run python manage.py runserver with my Django project with PostgreSQL. I have made sure to install all my node modules and dependencies, I have re-installed PostgreSQL using homebrew and have started my postgres. waiting for server to start....2020-03-11 13:49:40.157 EDT [88879] LOG: starting PostgreSQL 12.2 on x86_64-apple-darwin18.7.0, compiled by Apple clang version 11.0.0 (clang-1100.0.33.17), 64-bit 2020-03-11 13:49:40.159 EDT [88879] LOG: listening on IPv6 address "::1", port 5432 2020-03-11 13:49:40.159 EDT [88879] LOG: listening on IPv4 address "127.0.0.1", port 5432 2020-03-11 13:49:40.160 EDT [88879] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432" 2020-03-11 13:49:40.168 EDT [88880] LOG: database system was shut down at 2020-03-11 13:45:10 EDT 2020-03-11 13:49:40.171 EDT [88879] LOG: database system is ready to accept connections done server started But for whatever reason, I get the following: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/neme/.local/share/virtualenvs/project-azure-87EjIYum/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/Users/neme/.local/share/virtualenvs/project-azure-87EjIYum/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, … -
Mobile screen size alias links not working
ROBLEM: In Mobile screen size alias links are not working Description I have built a project (HTML, CSS, JS building tool) with https://bootstrapshuffle.com/ I have exported the project Put it in to a django project I have added a few extra buttons to the middle of the screen that are fusions as alias on the landing page. ERORR: This exported project perfectly works with all the buttons when it is in Desktop screen size or tablet screen size (both cases the original builder reorganizes the components). But when I shrink the screen size to the size of a mobile and it reorganizes the components it leaves these alias buttons that worked in both tablet and desktop mode but does not in this mobile screen size. I have read the following projects and I probably have something similar Href links do not transpire/work at mobile size screen media queries not working on mobile screen size Links not working on site when screen size is reduced The only issue is that I have that the downloaded project from the online editor only given me a bootstrap.min.css and bootstrap.min.css.map non of them is organized. Is there a way to make them organized and … -
Django Rest Framework drf-nested-routers example of Infinite-depth Nesting and Hyperlinks for Nested resources
I am quite new to django-rest-framework. I am trying to combine the examples infinite-depth nesting and hyperlinks for nested resources in drf-nested-routers I added a MailReply object just to try the infinite-depth nesting. My infinite-depth nesting works fine but i am getting confused by the nesting serializer relations. models.py from django.db import models class Client(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class MailDrop(models.Model): title = models.CharField(max_length=100) client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name='maildrops') def __str__(self): return self.title class MailRecipient(models.Model): name = models.CharField(max_length=100) mail_drop = models.ForeignKey('MailDrop', on_delete=models.CASCADE, related_name='mailrecipients') def __str__(self): return self.name class MailReply(models.Model): title = models.CharField(max_length=100) mail_recipient = models.ForeignKey('MailRecipient', on_delete=models.CASCADE, related_name='mailreplies') def __str__(self): return self.title I want to show the url of my objects like this, it's working but currently it's missing the url { "id": 1, "url": "/api/clients/2/" "name": "Client Name 1", "maildrops": [ { "title": "Mail Drop Title 1" } ] }, { "id": 2, "url": "/api/clients/2/" "name": "Client Name 2", "maildrops": [ { "title": "Mail Drop Title 2" } ] } I tried using NestedHyperlinkedModelSerializer instead of HyperlinkedModelSerializer in my custom serializers like what was suggested in the example for hyperlinks for nested resources both works. Also tried NestedHyperlinkedRelatedField instead of HyperlinkedRelatedField but like before it does the … -
Django app to perform Matrix operations [Beginner]
Design of the app. Click Here How can I make an app designed like this with Django? Please be detailed about the forms and I want the output to be displayed on the same page. -
cart added but is charged twice when checkout
I am having some issues with cart payment with stripe. When I checkout one product it is checking out two orders (no matter how many products I have within the cart). Here is the function I have to create a cart in session and error: from django.shortcuts import get_object_or_404 from tour_store.models import Destinations def cart_contents(request): """ Ensures that the cart contents are available when rendering every page """ cart = request.session.get('cart', {}) cart_items = [] total = 0 destination_count = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, pk=id) total += quantity * destination.price destination_count += quantity cart_items.append({'id': id, 'quantity': quantity, 'destination': destination}) #cart_item will loop into the cart. print(cart_items) print(destination_count) print(cart) return {'cart_items': cart_items, 'total': total, 'destination_count': destination_count} =====SHELL=============== {'1': 1} << NORMAL CART ADDED [11/Mar/2020 16:27:38] "GET /chekout/ HTTP/1.1" 200 12919 {'1': 1}. << DOUBLE THE CART AND CHARGE {'1': 1} [11/Mar/2020 16:28:59] "POST /chekout/ HTTP/1.1" 302 0 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 54962) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "/Users/macbook/software_projects/tour_project/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/macbook/software_projects/tour_project/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line … -
authentication problem with django and apache wsgi
I want to have a base authentication into my django application by apache's base auth. my config looks like this: <IfModule mod_ssl.c> <VirtualHost *:443> ServerName url.test.com ServerAdmin webmaster@localhost.com ProxyPass / http://127.0.0.1:8000/ ProxyPassReverse / http://127.0.0.1:8000/ WSGIDaemonProcess projectname \ python-home=/home/user/app/project/env \ python-path=/home/user/app/project:/home/user/app/project/env/lib/python3.5/site-packages/ WSGIProcessGroup projectname WSGIScriptAlias / /home/user/app/project/app/server/wsgi.py WSGIPassAuthorization On Alias /static/ /home/user/app/app/project/static/ ErrorLog ${APACHE_LOG_DIR}/error-log CustomLog ${APACHE_LOG_DIR}/access-log combined LogLevel info # Protecting with basic authentication <Location /> AuthType Basic AuthName "Restricted Content" AuthUserFile /etc/apache2/.htpasswd Require user testuser AuthBasicProvider wsgi WSGIAuthUserScript /home/user/app/project/app/server/wsgi.py </Location> SSLCertificateFile /etc/letsencrypt/live/project.app.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/project.app.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> and wsgi.py containing: import os import sys sys.path.insert(0, '/home/user/app/project') sys.path.append('/home/user/app/project/env/lib/python3.5/site-packages') os.environ["DJANGO_SETTINGS_MODULE"] = "project.app.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() with this setup I get the error message: AH01618: user testuser not found: / after some research I've seen that I probably should remove AuthBasicProvider and WSGIAuthUserScript from Location to: # Protecting with basic authentication <Location /> AuthType Basic AuthName "Restricted Content" AuthUserFile /etc/apache2/.htpasswd Require user testuser </Location> this leads to the password being accepted, but then I get a 403 error in the django application: Forbidden: / [11/Mar/2020 17:23:35] "GET / HTTP/1.1" 403 13 as I'm usually more on the coding side I'm not super familiar with the setup of the django application …