Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django settings.py
At my project login, some settings.py environment variables are loaded to enable some behaviors: unit_id = settings.COMPANY When another user logged in the system changes the value of this variable, through a function, it reflects in all other users who are already active: settings.COMPANY = "coke" in this case, all users will see "coke" in settings.COMPANY. I believed this would be in memory and would only apply to the user section in question, because I did not write in the physical file. I wonder if this is how Django handles the settings.py environment variables: Does it propagate dynamically to all instances opened by all users? -
how to control the for loop if the value is already detect?
\html <select id="payments" name ="payments" onchange="payment(this.value)"> <option value="0" name ="yearlvllist">-- Payment Type --</option> {% for paymentschedule in payment %} <option value="{{paymentschedule.Payment_Type.id}}" name ="payments">{{paymentschedule.Payment_Type}}</option> {% endfor%} </select> \views def scheduleofpayment(request): payment = ScheduleOfPayment.objects.all().filter(Education_Levels=paymentsid).order_by('Display_Sequence') return render(request, 'accounts/scheduleofpayment.html', {"payment":payment}) \models class ScheduleOfPayment(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.FloatField(null=True, blank=True) Remark = models.CharField(max_length=500,blank=True, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) def __str__(self): suser = '{0.Education_Levels}' return suser.format(self) this is the image from my admin-site admin-site this is the result of what i filter in schedule of payment user My problem is how to control the looping of monthly in html template? without deleting the database. do you have an idea guys ? -
What is the source of slow response time on client when server is fast, in Python web app hosted in Azure
I have a simple Python web app hosted in Azure. Here are the details: Azure App Service for Linux (Basic Service Plan - B1 with 1 core) Django framework Postgres backend via Azure Databases for PostgreSQL Uses Vue on the client-side All services are located in the same resource group Problem It is a simple app and the database queries take about 30ms, including the time to fetch. However, the app is performing quite slowly.The initial load time of the SPA in the client is around 10s, with subsequent requests taking around 7-8s. Troubleshooting I took a look at the response times in application insights and it seemed acceptable to me. I then took a look at the requests for a single page load. I noticed that while the individual responses for each API call were fast, there one about 1s between each request. I then tried various gunicorn configurations, changing the workers & threads. I settled on 1 worker with 4 threads. This improved performance to 1.5-2s per page load after the SPA loads. This is still not quite satisfactory, especially considering that applications insights suggests that the median response time is 160ms. I then scaled the app all … -
How to get related values in 3 Models Django
I have 3 models, Order, OrderDetail and Sale, in Sale I save the Order "id", and in the Sale DetailView I want to show all OrderDetails "products" related to that Order. My models: class Pedido(models.Model): total = models.DecimalField(max_digits=10, decimal_places=2, default=0) fecha = models.DateField(default=datetime.now, null=True, blank=True) estado = models.CharField(max_length=20, default='Pendiente') cliente = models.CharField(max_length=50, default='Agregue Cliente') observacion = models.CharField(max_length=200, null=False, default='Ninguna') class DetallePedido(models.Model): pedido = models.ForeignKey(Pedido, db_column='pedido_id', on_delete=models.SET_NULL, null=True) producto = models.ForeignKey(Producto, db_column='producto_id', on_delete=models.SET_NULL, null=True, verbose_name='Productos') cantidad = models.DecimalField(max_digits=10, decimal_places=0, default=1) precio = models.CharField(max_length=200, default=0) class Venta(models.Model): fecha = models.DateField(default=datetime.now, null=True, blank=True) pedido = models.ForeignKey(Pedido, db_column='pedido_id', on_delete=models.SET_NULL, null=True) total = models.CharField(max_length=200, default=0) cliente = models.CharField(max_length=100) nit = models.CharField(max_length=10) In the Order DetailView im getting all the "products" in OrderDetail like this: {% for producto in pedido.detallepedido_set.all %} code.. How can I show all the products related in the Order saved in the Sale? -
paginator reset query as i change page
I am developing an app in Django. I have a template in which are displayed data from my model. The template has a search bar and also a paginator. The problem is that, when I run a query (let's say I search for the word "home"), it shows the filtered results for page one, but as I click on my paginator to get to the next page, the query gets reset, and I get page 2 of unfiltered data (entire data). How can I fix it? Here is my paginator code: <nav aria-label="..."> <ul class="pagination"> {% if all_entries.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">&laquo; first</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ all_entries.previous_page_number }}">{{ all_entries.previous_page_number }}</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" class="page-item disabled">&laquo; first</a> </li> <!-- <li class="page-item disabled"></li> <a class="page-link" href="#" class="page-item disabled">previous</a> </li> --> {% endif %} <li class="page-item active"> <a class="page-link" href="#">{{ all_entries.number }}<span class="sr-only">(current)</span></a> </li> {% if all_entries.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ all_entries.next_page_number }}">{{ all_entries.next_page_number }}</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ all_entries.paginator.num_pages }}">Last [ {{ all_entries.paginator.num_pages }} ] &raquo;</a> </li> {% else %} <!-- <li class="page-item disabled"></li> <a class="page-link" href="#" class="page-item disabled">next</a> </li> --> <li class="page-item disabled"> <a class="page-link" … -
Python social auth: default Django backend doesn`t authenticate users
I want to add authentication with different auth providers to my Django project, so I decide to use python-social-auth. I’ve configured my settings.py as mentioned in an official docs. And Django ModelBackend never authenticates a user! settings.py: AUTHENTICATION_BACKENDS = ( 'social_core.backends.backends.GithubOAuth2', 'django.contrib.auth.backends.ModelBackend', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR.child('templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] SOCIAL_AUTH_USER_MODEL = 'users.models.CustomUser' SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GITHUB_KEY = '...' SOCIAL_AUTH_GITHUB_SECRET = '...' # don`t want to create users SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) urls.py: urlpatterns = [ ... path('social/', include('social_django.urls', namespace='social')), ... ] template: <a href="{% url "social:begin" "github" %}">Login with GitHub</a> It happens cause social_core doesn`t put a username and password arguments to the authenticate method, ModelBackend always fails in getting users. Passed arguments are backend instance, storage instance and response from GitHub. Ok, so I decided to make my own auth backend. class SocialAuth(ModelBackend): def authenticate(self, request, **kwargs): backend = kwargs.get('backend') response = kwargs.get('response') username = backend.get_user_details(response)['username'] return UserModel.objects.get_by_natural_key(username) And it works well then I get some errors with user.social_user attribute, but I guess it`s too much for one question. So, why all … -
CSS changes not appearing - Django
When I make new changes to my css the new changes are not showing. If i delete a style it still shows and if I delete my <link> tag all the styles disappear. I can edit styles with inspect element but the same changes do not show if I edit my style sheet. This is strange because it shows old styles only. settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') base.html {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> -
Rendering a pandas dataframe on-page in django
I have created a page with Django where you can upload an excel file and it will save into the /media folder. Once it's uploaded, there is a page that shows a table of the uploaded files. I have added a 'View' button, and the expected behavior would be to pd.read_excel, then do a df.to_html, and then render that html on the same page. There have been several other questions regarding how to do this, but they don't seem to fit my specific use case. Any help you can provide on making the function and rendering it would be greatly appreciated! Thank you. -
django form: CheckboxSelectMultiple's id_for_label does not work
I want to customize my label style, so I overwrite {{ form }} in my html template with a for loop through all choices. But I found I lost label 'for' attribute and 'id' of the input for each choice after using for loop. Old codes: html template: {% block form %} <button class="checker">Uncheck all</button> <button class="allChecker">Check all</button> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <br/> <input type="submit" value="Submit"> </form> {% endblock %} my form: class RerunForm(forms.Form): items = ItemStatus( queryset=models.Container.objects.none(), widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')), help_text="Select requirements/objectives that you want to rerun.", ) def __init__(self, rerunqueryset, *args, **kwargs): super(RerunForm, self).__init__(*args, **kwargs) self.fields['items'].queryset = rerunqueryset class ItemStatus(models.ModelMultipleChoiceField): def label_from_instance(self, obj): if '_' not in obj.name: return "{} ({})".format(obj.name.replace('-r1', '').replace('-s1', ''), obj.state) else: return ". . . {} ({})".format(obj.name.replace('-r1', ''), obj.state) New Codes: html template: {% block form %} <button class="checker">Uncheck all</button> <button class="allChecker">Check all</button> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <ul id="id_items"> {% for value, label, item in form.items.field.choices %} <li> <label for="{{ form.items.id }}"> <input type="checkbox" value={{ value }} name="items" id="{{ form.items.auto_id }}"> <span class="listItem-{{item.state}}">{{ label }}</span> </label> </li> {% endfor %} </ul> <br/> <input type="submit" value="Submit"> </form> {% endblock %} new form: class RerunForm(forms.Form): items = ItemStatus( queryset=models.Container.objects.none(), widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')), help_text="Select … -
Save data in 1 api post call using django rest framework
I have 3 tables in a sequence with foreign keys like this 1st table class Orders(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True) order_number = models.AutoField(primary_key=True) total_amount = models.DecimalField(max_digits=10, decimal_places=2) 2nd table is which will keep record of articles for sale class OrderArticle(models.Model): order = models.ForeignKey(Orders, on_delete=models.CASCADE) article = models.ForeignKey(Articles, on_delete=models.CASCADE) article_quantity=models.IntegerField(default=0) prize=models.DecimalField(max_digits=10, decimal_places=2) 3rd table is option of Articles which can be added to articles every article have its own options class OrderArticleOptions(models.Model): article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE) order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE) article_option_quantity = models.IntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2) Now I want to add data in this using Django rest framework .I am adding data into Order table like this Serilizer.py is class OrderSerializer(serializers.ModelSerializer): restaurant=RestaurantSerializer(required=False) article=ArticlesSerializer(read_only=True, source='orderarticle_set' , many=True) total_amount=serializers.DecimalField(required=False,max_digits=5, decimal_places=2) tableid=serializers.IntegerField(required=False) class Meta: model = Orders fields = [ 'order_number' , 'tableid' , 'total_amount' , 'ordertime' , 'order_status' ,'restaurant', 'article' ,] def create(self, validated_data): tableid = validated_data.get('tableid') total_amount = validated_data.get('total_amount') order_status = validated_data.get('order_status') restaurant = validated_data.get('restaurant') order_obj = Orders.objects.create(tableid=tableid, total_amount=total_amount,order_status=order_status, restaurant=restaurant ) return order_obj And my view.py is class CreateOrderApi(APIView): def post(self, request,restid): serializer = OrderSerializer( data=request.data) if serializer.is_valid(): obj_order = serializer.save(restaurant=Restaurant.objects.get(id=restid)) So Now I want to add data into all three tables , relation is In one order I … -
Upload multi img to 1 post on Django ? How do that?
I want to upload multi img to 1 post on Django. I used ImageField in models.py. But it's just can upload 1 image to 1 post. How can i upload multi image to 1 post with Django or someways to solved that problem. Thank you so much. -
dataSource in mat Table using Angular Material in Angular 8 get method
i try to create a Mat Table using Angular and Django for build a filter and pagination method,etc. the thing is this i'm using Django like backend and Angular Fronted, and i have the method Get ,Insert, Alter and Delete. all that method is work 100% ,but i don't have idea how i can make the filter using that methods for build the filter and pagination buttons. i need know, if i can build a filter method for example using only the fronted or i need both for make the method. service .ts baseurl = "http://127.0.0.1:8000"; constructor(private http: Http, private httpClient: HttpClient) { } private headers = new Headers({ 'Content-Type': 'application/json', Authorization: `JWT ${localStorage.getItem("token")}` }); getDoctores(): Promise<Doctor[]> { return this.http.get(this.baseurl + '/doctor?format=json', { headers: this.headers }) .toPromise() .then(response => response.json() as Doctor[]) } deleteDoctor(id: number): Promise<void> { const url = `${this.baseurl + "/doctor"}/${id}`; return this.http.delete(url, { headers: this.headers }) .toPromise() .then(() => null) } createDoctor(d: Doctor): Promise<Doctor> { return this.http .post(this.baseurl + "/doctor", JSON.stringify(d), { headers: this.headers }) .toPromise() .then(res => res.json() as Doctor) } updateDoctor(doctores): Observable<any> { const body = { nombreDoc: doctores.nombreDoc, apellidoDoc: doctores.apellidoDoc, rutDoc: doctores.rutDoc, release_date: doctores.release_date, direccionDoc: doctores.direccionDoc, telefonoDoc: doctores.telefonoDoc }; return this.http.put(this.baseurl + '/doctor/' + … -
How can I make a Google Map marker redirect to a URL?
Here is my html: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <style> /* Set the size of the div element that contains the map */ #map { height: 700px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> <!--The div element for the map --> flavor <div id="map"></div> <script> // Initialize and add the map function initMap() { var map = new google.maps.Map( document.getElementById('map'), {zoom: 4, center: {'lat': 42.6803769, 'lng': -89.03211}}); {% for Listing in posts %} new google.maps.Marker({position: {'lat': {{ Listing.lat }}, 'lng': {{ Listing.lng }}}, map: map}); {% endfor %} } </script> <!--Load the API from the specified URL * The async attribute allows the browser to render the page while the API loads * The key parameter will contain your own API key (which is not needed for this tutorial) * The callback parameter executes the initMap() function --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBvYLD6Huu01-tspszRu-eoCKhWTMnvfXU&callback=initMap"> </script> {% endblock %} I need to make the line: new google.maps.Marker({position: {'lat': {{ Listing.lat }}, 'lng': {{ Listing.lng }}}, map: map}); redirect to /preview/{{ Listing.pk }} when clicked. How can I make my … -
Django_filters multiple arguments for non-model field
I need my endpoint to accept queries in the format: groupId=11111&groupId=22222 and resolve to a query: groupId=1111 OR groupId=2222 I couldn't find anything in the documentation on how to do this, and made the following implementation (currently WIP, haven't written many tests): 2 from django_filters import rest_framework as filters 32 class CustomFilter(filters.UUIDFilter): 33 def filter(self, qs, value): 34 if "groupId" not in self.parent.data: 35 return super().filter(qs, value) 36 37 q = Q() 38 for val in self.parent.data.getlist("groupId"): 39 q |= Q(**{f"{self.field_name}__{self.lookup_expr}": val}) 40 return self.get_method(qs)(q) Used like: 45 groupId = CustomFilter(field_name="group_id", help_text="Jobs associated with group") I have two questions: Is there a way to implement this using what is already in the framework? Is there a way of finding the field name on the request? (groupId instead of group_id) -
How to mimic Python's open(filename, 'r') in Django context on uploaded file?
I have tried parsing same GPX file both in and outside of Django context. In a standalone script everything works fine while reading the file in the default text mode: import gpxpy def coordinates_from_GPX(gpx_file): gpx = gpxpy.parse(gpx_file) coordinates = [] for track in gpx.tracks: for segment in track.segments: for point in segment.points: latlng = point.latitude, point.longitude coordinates.append(latlng) return coordinates gpx_file = open('oldrichov.gpx', 'r') # note the 'r' mode coordinates = coordinates_from_GPX(gpx_file) print(coordinates) However, in Django context, I am getting an error while trying to parse the same GPX file uploaded via model form: import gpxpy def have_I_been_there(request): '''Shows the intersection between activities polylines and uploaded GPX ''' if request.method == 'GET': form = GPXFileForm() elif request.method == 'POST': form = GPXFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_gpx = form.save() gpx = gpxpy.parse(uploaded_gpx.file.open(mode='rt')) # ERROR HERE coordinates = coordinates_from_GPX(uploaded_gpx) print(coordinates) context = { 'form': form, } return render(request, 'explorer/have_I_been_there.html', context) Traceback (most recent call last): File "M:\django\newenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "M:\django\newenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "M:\django\newenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "M:\django\strava_explorer\explorer\views.py", line 504, in have_I_been_there coordinates = coordinates_from_GPX(uploaded_gpx) File "M:\django\strava_explorer\explorer\views.py", line 514, in coordinates_from_GPX gpx = gpxpy.parse(gpx_file) … -
How to use JavaScript variable as django tags template parameter?
f I use the code as follows it works: function filter() { var assuntos = document.getElementById("assuntos").value var data = '{{ "CONTRATOS"|filter_assuntos }}'; change(data); }; but how do I use my assuntos variable instead ofCONTRATOS? -
Django DRF, changing authentication schemes from JWT to basic token
I have a Django app that was originally using drf token authentication. Everything was working perfectly. Then I decided to switch to JWT's. I made all the changes and everything was working perfectly. I changed a bunch of code, updated my git and all that, then decided that the drf token auth actually was the better choice. So I changed the authentication classes back, and removed the JWT-specific urls, but every postman request still gives me the JWT denied message: "detail": "Authentication credentials were not provided." It seems that something internally is not being reset by just changing the authentication classes back. I deleted my sqlite file and ran both makemigrations and migrate but still I get the same error. How can I fix this without checking out the old branch of my git (which would lose a bunch of changes I made to the app)? Here is the relevant section of my settings file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'prototype', 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } -
Nginx: No such file or directory
I have a vps server by Reg.ru and domain by freenom. On the Reg.ru I added domain via dnsadmin. All right. Notes are created. Status - synchronized. On the freenom in the management panel of domain are next fields: Name, Type, TTL, Target. Name - empty, TTL - 3600, Type - A, Target - ip of vps server. Status - active. Nginx /etc/nginx/sites-available/myproject and /etc/nginx/sites-enabled/myproject server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } /etc/nginx/nginx.conf ... http { ... include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*.*; } nginx -t - successful systemctl status nginx - active ufw status Status: active To Action From -- ------ ---- 8000 ALLOW Anywhere 80 ALLOW Anywhere 443 ALLOW Anywhere 8000 (v6) ALLOW Anywhere (v6) 80 (v6) ALLOW Anywhere (v6) 443 (v6) ALLOW Anywhere (v6) When I open ip of vps-server in browser I get home page of nginx. gunicorn /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/home/myproject ExecStart=/home/myproject/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-enabled# cat /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target systemctl status gunicorn … -
How to save two forms in one model in Django?
I have two Django forms of the same model in the same view, so when I try to save them I get two objects of the model and my goal is to get one single object with the data of both forms. I've tried to save both forms separately, which lead to creating two objects. Also, I've thought of saving one form and then updating the second one but I just don't know how to do that. if request.method == 'POST': animal_form_required = AddAnimalFormRequired(data=request.POST) animal_form_optional = AddAnimalFormOptional(data=request.POST) if animal_form_required.is_valid() and animal_form_optional.is_valid(): animal_required = animal_form_required.save(commit=False) animal_required.save() animal_optional = animal_form_optional.save() animal_optional.save() return render(...) animal_required and animal_optional are the two forms and animal is the model. Both forms have different attributes of the animal. After doing this, I get two objets of animal: one with the animal_requiredattributes and one with the animal_optional attributes. How can I get one single object of animalwith all the attributes? Thanks so much in advance! -
(Django) Displaying multiple generated forms (unknown quantity) in the view, and retrieving their results?
I'm currently attempting to display a set of generated forms into the view. So take the following view, for example (as part of a TemplateView class): def get(self, request, id): df = create_dataframe(User.objects.get(user=request.user.username)) context = generate_context_forms(df=df, user=request.user.username) return authentication_check( request=request, template_name=self.template_name, context=context ) In essence, the create_dataframe function generates some relevant calculations using some user-inputted data, and that data designates how many forms I will be generating for the user. The generate_context_forms function utilizes that DataFrame to generate the context for the user. Typically, a context will look like so: context = { 'general': GeneralForm, 'specific1': SpecificForm, 'specific2': SpecificForm, ... } To n amounts of SpecificForm. What I am trying to do is display all of the specific forms to the user without causing loss of control. All the forms will be submitted by a single "submit" button, and after submission, I must gather all of the data they individually submitted. With the context above, I do not know how I would iterate through all the specific forms in the context. Another attempt I did was to simply add the specific forms to a list: context = { 'general': GeneralForm, 'specific': [SpecificForm, SpecificForm, ...], } But it seems that when … -
Django Forms - Get object if exist - Unique Field - M2M
I'm still a junior with django. Please explain in detail :D I'm developing a system to manage Full Days for restaurants. A full day can have many guests, and a guest can have many full days. M2M Relationship. ============== My model's class Full_day(models.Model): by = models.ForeignKey('users.System_user', on_delete=models.CASCADE) guests = models.ManyToManyField('users.Guest', verbose_name='Huespedes') bussines_unit = models.ForeignKey( 'administration.Bussines_unit', on_delete=models.CASCADE, verbose_name='Unidad de Negocio') type_full_day = models.ForeignKey(cat_full_day, on_delete=models.CASCADE) created = models.DateField( auto_now=True, auto_now_add=False, verbose_name='Creado el') modified = models.DateField( auto_now=False, auto_now_add=True, verbose_name='Modificado el') class Guest(models.Model): stature_choices=( ('+ 1.20', '+ 1.20 M'), ('- 1.20', '- 1.20 M') ) name = models.CharField(max_length=50, verbose_name='Nombre') document_id = models.PositiveIntegerField(unique=True, verbose_name='Cedula/Documento Identidad', blank=True, null=True) stature = models.CharField(verbose_name='Estatura', choices = stature_choices, max_length=6) created = models.DateField(auto_now=True, auto_now_add=False, verbose_name='Creado el') modified = models.DateField(auto_now=False, auto_now_add=True, verbose_name='Modificado el') The Problem As you can see the "document_id" must be unique, I want to make the view get to the guest if it already exists and the name entered is identical to the DB, to assign it to the full day. The number of guests for the Full day depends on the type of full day, I have already solved it with a GET (see it in the View), and I have rendered the amount of GuestForm's according to … -
Why user.save() don't save into database
I want to save customer_id from stripe into my user model, but when call user.save() nothing happen. Here my user model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name=_('Email address'), max_length=255, unique=True, ) first_name = models.CharField(_('First name'), max_length=20) last_name = models.CharField(_('Last name'), max_length=20) is_active = models.BooleanField(_('Active'), default=True) date_joined = models.DateTimeField(_('Date joined'), auto_now_add=True) is_deleted = models.BooleanField(_('Deleted'), default=False) stripe_customer_id = models.CharField(_('Stripe customer id'), max_length=19, null=True, default=None) Here fragment of code where I create Customer in Stripe and want save id into model: user = User.objects.get(pk=request.user.pk) ... if not user.stripe_customer_id: customer = stripe.Customer.create( email=user.email, name=user.first_name + " " + user.last_name, source=stripe_token ) user.stripe_customer_id = customer.stripe_id user.save() Any ideas why it's not saving ? -
Django - Invalid block tag..'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I'm having trouble loading this. I'm fairly new to python and it's formatting. I've checked previous questions where it seems to be a syntax error but I can't see any formatting issues. The code is taken straight from the Django tutorial https://docs.djangoproject.com/en/2.2/intro/tutorial06/ {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li></ul> {% else %} <p>No polls are available.</p> {% endif %} -
No connection adapters were found for '<QuerySet
Models class URL_monitor(models.Model): url = models.TextField(unique=True, verbose_name='URL') interval = models.PositiveIntegerField(verbose_name='Interval (in seconds)') def __str__(self): return self.url def get_absolute_url(self): return reverse('index') View def IndexView(request): urls = URL_monitor.objects.all() response = requests.get(urls) status = response.status_code context = { 'urls' : urls, 'status' : status, } return render(request, 'index.html', context) Template {% if urls %} {% for url in urls %} <p>Status: {{ status }} {{ url.url }} <a href="{% url 'delete_url' url.pk %}">Delete</a></p> {% endfor %} {% else %} <p>No URL's added, <a href="{% url 'add_url' %}">add some</a></p> {% endif %} I just want to get an url from my model and get a status code for it. My url field in database has a value: http://google.com/ -
Getting model instances in view DRF
I have a Cart model like this class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='items', null=True) quantity = models.PositiveIntegerField(default=1) here quantity is default value is one so, everytime user does not need to add quantity to the cart. If user does not add quantity it should take default But I cannot get this default value in the view class CartApiView(generics.ListCreateAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer def post(self, request, pk=None, *args, **kwargs): serializer = CartSerializer(data=request.data) if serializer.is_valid(): try: product = Product.objects.get(pk=request.data['product']) quantity = int(self.request.GET.get('quantity')) print(quantity) except Exception as e: print(e) return Response({'status': 'fail'}) if product.inventory <= 0 or product.inventory - quantity < 0: print('There is no inventory to fill this request') return Response({'status': 'out of stock'}) here what I have tried so far but it does not working I did request.data, self.kwargs.get() with these it also did not work. Any idea plz?