Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when i want to extract information from query results in django it return none
I want to get the column of result, it prints fine in views, but return nothing in ajax, i don't know why?, there are a same type of function that works fine, but it didn't. def requiredfield(request): total_ms=['pratap'] # #print(T) name = ['jay'] print(name) print(total_ms) if request.method == "POST": datafiles = request.POST.get('datafiles') print(datafiles) query = 'select id, Must_Have from analytics_fileuploadrequiredata where DataFiles_Name = ' + '"' + datafiles + '"' #query = 'select id, Functions from analytics_analyticsreport' print(query) result = FileUploadRequireData.objects.raw(query) for i in range(len(result)): ms = result[i].Must_Have if ms not in total_ms: total_ms.append(ms) print(total_ms) return JsonResponse(total_ms, safe=False) -
Server-to-server communication with RasPi and Python
I am aware of frameworks like Django and Flask that manage all the GET requests etc but how do I communicate between two servers without a framework full of nonsense I don't need. I'm trying to set up a drone with motors, photos that need sending and remote control via the server at home which is accessed over the internet via a proxy for security. I'm focusing on the RasPi though. -
Server communication with Python on RasPi
I am aware of frameworks like Flask and Django that manage all the GET requests etc but how do I communicate between two servers without a framework full of nonsense I don't need. I'm looking to finish my server-controlled drone which sends pictures and is controlled via the server but all in Python. -
NoSQL or SQL for eCommerce sites' product price comparison ( with Django)?
I'm trying to build a project for comparing product prices among different e-commerce sites of our local area. I'm using Scrapy for crawling data from different e-commerce sites and now needs to store those data into a database. I'm not sure which type of database I need to store information like below: product_title product_link product_image product_price Any kind of suggestion would be much appreciated. Note: I am using Django for back-end and Scrapy for data scraping. -
Django form, use data in field from other model
How to fill field in form based on model id? I have to models. Match and Match Register. Logged user can register for match, the data is written in Match Register model. I am now creating form for editing Match object and want to populate fields referee_a and referee_b with values from Match Register table (for edited match of course). I don't know how to to do this exaclty. Could you please help me with it? class MatchForm(forms.Form): class Meta: model = Match fields = ('match_number', 'home_team', 'away_team', 'match_category', 'date_time', 'notes', 'referee_a', 'referee_b') widgets = { 'match_number': forms.TextInput(attrs={'class': 'form-control'}), 'home_team': forms.Select(attrs={'class': 'form-control'}), 'away_team': forms.Select(attrs={'class': 'form-control'}), 'match_category': forms.Select(attrs={'class': 'form-control'}), 'date_time': forms.DateTimeField(attrs={'class': 'form-control'}), 'referee_a': forms.Select(attrs={'class': 'form-control'}) 'referee_b': forms.Select(attrs={'class': 'form-control'}) 'notes': forms.Textarea(attrs={'class': 'form-control'}) } class MatchRegister(models.Model): match = models.ForeignKey( Match, on_delete=models.SET_NULL, null=True ) ref_reg = models.ForeignKey( User, on_delete=models.SET_NULL, null=True ) -
Django channels sends 403 instead of 404
I'm just starting with django channels and I would like in case of error that django channels sends a 404 instead of a 403 when closing without accepting connection. class MyConsumer(AsyncWebsocketConsumer): async def connect(self): if False: await self.accept() await self.close() Client side, when I connect to this socket, I get 403 and I want to receive 404: b'HTTP/1.1 403 Access denied\r\n' There is probably something basic I don't get. -
No .sock file is being created by my gunicorn service
I have the following problem while hosting my website. I configured all the things .conf files here: gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=user Group=nginx WorkingDirectory=/root/myproject ExecStart=/root/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:/root/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target and my nginx.conf server { listen 80; server_name agros.uz www.agros.uz; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/myproject/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/root/myproject/myproject.sock; } } However I am having the following error unix:/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 37.9.113.208, server: agros.uz, request: "GET /uz/insurance?type=physical&page=2&page=7&page=6&page=8&page=4 HTTP/1.1", upstream: "http://unix:/root/myproject/myproject.sock:/uz/insurance?type=physical&page=2&page=7&page=6&page=8&page=4", host: "agros.uz" When I access the domain this error happens 502 Bad Gateway error and the .sock file is not being created in /root/myproject/myproject.sock as it mentioned in my gunicorn.service file. -
Django built-in authentication for reset password link chopping off token in url
I am using built-in Django authentication to send an email to reset a password. Sending the email works, but when I try and follow the link to the page to reset my password, Django changes the URL (kind of like a redirect I guess) and then is trying to resolve the URL to 'http://127.0.0.1:8000/registration/USER_ID/set-password', instead of 'http://127.0.0.1:8000/registration/USER_ID/TOKEN'. Django then throws an error: 'NoReverseMatch at /registration/reset/USER_ID/set-password/' I don't have a file called "set-password" and nowhere in my code (templates, URLconf) do I have "set-password". urlpatterns = [ ... ... path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] I am using the code found in the docs (https://docs.djangoproject.com/en/2.1/topics/auth/default/#using-the-views) for my URL matching, so I am not creating anything new. It seems like Django is removing the token from the URL? -
Send custom signal on updating record in DRF view
I'm using Django 2.x and DRF. I have created a signal and want to send it when the record is updated and created. Below is my ViewSet with two methods update and perform_create. class AmountGivenViewSet(LoggingMixin, viewsets.ModelViewSet): serializer_class = AmountGivenSerializer def update(self, request, *args, **kwargs): obj = self.get_object() request.POST._mutable = True if 'mode_of_payment' not in request.data: request.data['mode_of_payment'] = obj.mode_of_payment_id request.POST._mutable = False return super().update(request, *args, **kwargs) def perform_create(self, serializer): contact = serializer.validated_data.get('contact') if contact.user != self.request.user: raise ValidationError({'contact': ['Contact does not exists']}) obj = serializer.save() given_amount_updated.send( sender=self.__class__, instance=obj, amount=self.request.data.get('amount', None), action='given' ) The signal should be sent only when the record is successfully created or updated. I'm able to send the signal in perform_create() method by putting after serializer.save() but how to do this in update(). Also I want to send updated obj as instance to the signal. -
Django: error_messages is not changing in form
I need to change the error_messages on a form from english to spanish. I've found this similar question: Django - change field validation message And I'm using it's second option 2.1. but It is not working, why? my_default_errors = { 'required': 'Este campo es obligatorio', 'invalid': 'Ese nombre de usuario ya está tomado' } class SignUpForm(UserCreationForm): first_name = forms.CharField(label= "Nombre", max_length=100, required=True) last_name = forms.CharField(label = 'Apellido', max_length=100, required=True) username = forms.CharField(label='Nombre de usuario', max_length=100, required=True, error_messages=my_default_errors) email = forms.EmailField(label='Correo electrónico', max_length=60, required=True) password1 = forms.CharField(label = 'Contraseña', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirmar contraseña', widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2') -
How to make DjangoTemplates work recursively
I have a template home.html which is the view of an app in Django. Now, I've added some templating in the html file to allow dynamic generation of HTML. For example I use {% load static %} and then href="{% static "path/to/resources" %}". So, when I open the app, after running the server, the path is dynamically created. Now, the problem is that the static files, that are dynamically loaded, also need to load other static files (and extend a template as well). I thought that DjangoTemplating might be working recursively, and will work on the called file too, but sadly that is not true. So, what should I do to make sure that all my templating logic is taken into consideration by Django, and is allowed to run? home.html snippet: {% load static %} <area alt="andhra" title="Andhra Pradesh" name="andhra" href="{% static "personal/pages/andhra.html" %}" shape="poly" ... /> andhra.html looks something like: {% extends "personal/post.html" %} {% blockcontent %} <style> #slider { width: 80%; .... <div class="carousel-inner"> <div class="carousel-item active"> {% load static %} <img class="d-block w-100" src="{% static "personal/images/andhraImages/1911-1915.jpg" %}" alt="First slide"> </div> ... {% endblock %} Which wants to extend the template:post.html which has {% blockcontent %}and {% endblock … -
Django override Save() Split into 3 separate entries
I have a model for Website which takes a domain_name entry class Website(models.Model): domain_name = models.URLField(unique=True) sub_domain =models.CharField(max_length=56, blank=True, default='') suffix = models.CharField(max_length=56, blank=True, default='') I'm then trying to split the domain parts using tldextract which is working well, on entry of a website by a user i want to store the sub_domain, domain and the suffix, so I've tried a lot of ways but can't seem to get the individual values stored def __str__(self): return self.name def validate_and_split_domain(self): domain = self.domain_name.lower() # make all lower case because django isn't case sensitive values = list(tldextract.extract(domain)) #Split values into a list self.sub_domain, self.domain_name, self.suffix = values[0], values[1], values[2] def save(self, *args, **kwargs): self.validate_and_split_domain() super(Website, self).save(*args, **kwargs) -
Django form update to secondary table(model)
I would like my Django form on 'POST' of results to update my PlayerPoints value to +3 for ALL the players on the winning team. The results model has a:- 'matchdate' field = foreignkey to MatchDaySquadRed or Blue model (which also has my playername field = foriegnkey to Player model), 'winningteam' field foreignkey to Team model, So for each result I should be able to find all the players in the winningteam, then add + 3 to the PlayerPoints model for that player. How do I first retrieve a list of all winning players by joining 3 tables (result, MatchDaySquad, Player). Then with that data update all the players in the PlayerPoints table to + 3 in one go. The models are listed below. Could I have a worked example please. class MatchDay(models.Model): matchdate = models.DateField(primary_key=True) FIVEASIDE = '5' EIGHTASIDE = '8' MATCH_CHOICE = ( (FIVEASIDE, '5-a-side'), (EIGHTASIDE, '8-a-side'), ) matchtype = models.CharField( max_length=10, choices=MATCH_CHOICE, default=FIVEASIDE, ) class MatchDaySquadRed(models.Model): matchdate = models.ForeignKey(MatchDay, null=True, blank=True, on_delete=models.SET_NULL) playername = models.ManyToManyField(Player) teamname = models.ForeignKey(Team, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return '%s' % (self.matchdate) class MatchDaySquadBlue(models.Model): matchdate = models.ForeignKey(MatchDay, null=True, blank=True, on_delete=models.SET_NULL) playername = models.ManyToManyField(Player) teamname = models.ForeignKey(Team, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return … -
Use a file input for a text field?
I have a Django model with a TextField. When I use a ModelForm to collect data to add/edit this model, I get a textarea in the HTML form, but I'd like to use a file input instead. I think what I need to do is to set the widget for this field on my form class using django.forms.FileInput, or maybe a subclass of that input, but it isn't clear to me how to make this work (and I'm not positive this is the right approach). So, how can I use a file input to collect data for a model using a ModelForm? -
How to rank myself as a software engineer?
Working with many software engineers around, How do I rank my self or How do I determine the levels of my skills. -
Using Django, how to count amount of free shelf space using a queryset?
Im developing an inventory management web app that allows teams, within an organisation, to be assigned boxes to store things in. There are multiple storage rooms and multiple shelves and sections. Every box is assigned a project. I would like to write a queryset in Django that shows how many empty spaces there are in a given room (how many locations there are that do not have boxes assigned to them) e.g. for the above picture showing room A Room: A Empty Spaces: 4 Here is a simplified version of my code: HTML: {% for each_space in Room_data %} { <p>"Room": "Room {{each_space.loc_room}}",</p> <p>"Empty Spaces": *** HERE I NEED HELP ***,</p> }, {% endfor %} Model: class Location(models.Model): loc_room = models.CharField() loc_section = models.IntegerField() loc_shelf = models.CharField() class Box(models.Model): box_contents = models.CharField() project_assigned_to = models.ForeignKey() Location = models.OneToOneField() class Project(models.Model): project_name = models.CharField() project_manager = models.ForeignKey() Views: def dashboard(request): Room_data = Location.objects.all() return render(request, 'main_app/dashboard.html' , {"Room_data":Room_data}) I've been stuck on this for a lot of today so I was hoping somebody might know the best direction forward. Thank you in advance. -
Use REMOTE_USER and traditional Django user at the same time
What's the best way to use django.contrib.auth.middleware.PersistentRemoteUserMiddleware with every connected user AND the traditional Django login user system? I understand that I need to keep two authentication backends in settings: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend', # Access via remote_user 'django.contrib.auth.backends.ModelBackend', # If the previus fails, access via model (REQUIRED FOR SUPERADMIN IF USER IS AnonymousUser!!!) ] But how use @login_required decorator properly? I have already read the docs here but they are not useful. -
Didn't working in inclusion tag with API. Did not receive value(s) for the argument(s): 'request'. Django 2.1.5
I want to get weather for cities (with ip and API) and redirect it to base template. I do this with include_tag. But crashes TemplateSyntaxError at /post/ 'city_weather' did not receive value(s) for the argument(s): 'request'. weather.py PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', ) @register.inclusion_tag('post/weather_tpl.html') def city_weather(request): remote_address = request.META.get('REMOTE_ADDR') ip = remote_address x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: proxies = x_forwarded_for.split(',') while (len(proxies) > 0 and proxies[0].startswith(PRIVATE_IPS_PREFIX)): proxies.pop(0) if len(proxies) > 0: ip = proxies[0] reader = geoip2.database.Reader('post/GeoLite2-City_20190108/GeoLite2-City.mmdb') try: city = reader.city(ip).city.name except: city = "London" url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&lang=ru&appid=**********************' city_weather = requests.get(url.format(city)).json() weather = { 'city' : city, 'temperature' : str(city_weather['main']['temp'])+'°C,', 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'] } next = request.META.get('HTTP_REFERER') if next: next = urlunquote(next) if not is_safe_url(url=next, allowed_hosts={request.get_host()}): next = '/' return {'next_page': next, 'city': city, 'weather' : weather } weather.html {{ next }} {{ city }} {{ weather }} base_generic.html ... {% load all_comments %} {% city_weather %} ... -
Django Models, Gathering models.AutoField number while overriding save() method
I have a Django Model for Users and then a Separate model for AccessLevels. When saving a User using Django's ORM, I want to also place an entry in the AccessLevels table. My issue is that the PK of AccessLevels is the PK of Users and I cannot seem to override the save() method and gather the value of id = models.AutoField(primary_key=True). Here is my relevant code: class Users(models.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # pk id = models.AutoField(primary_key=True) # client_id client_id = models.IntegerField(null=False, blank=False, default="-1") ... def save(self, *args, **kwargs): AccessLevel(user_id=self.id, client_id=self.client_id).save(using='default') print('Access Level Set for User while saving') super(Users, self).save(*args, **kwargs) Here is the important part of AccessLevel class AccessLevel(models.Model): # pk id = models.AutoField(primary_key=True) # this is the id for the user, but I get null value user_id = models.IntegerField(null=False, blank=False, default="-1") client_id = models.IntegerField(null=False, blank=False, default="-1") When I call this code I get the error. root_user = Users(username='root', email='root', first_name='root', last_name='root', phone='root', password=make_password(default_root_pw), type='root').save(using='default') Here is the error django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (3, null, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0). -
create view of oneToMany object in related object view
I have a questionnaire, containing many questions with their answers. My main objective is to create a webpage where I can show the details of a questionnaire with the list of rules (question/answer) and in the bottom of the page I want to call the create rule page: def create_rule_view(request, id, sc_id): if request.method == "POST": input = InputForm(request.POST) answer = AnswerForm(request.POST) rule = RuleForm(request.POST) if rule.is_valid() and input.is_valid() and answer.is_valid(): r = rule.save() i = input.save(commit=False) a = answer.save(commit=False) i.rule_id = r i.save() a.rule_id = r a.save() question = input.cleaned_data["patterns"] else: input = InputForm() answer = AnswerForm() rule = RuleForm() return render(request, "rule/create_rule.html", { 'rule': rule, 'input': input, 'answer': answer }) def detail_scenario(request, id, sc_id): object = get_object_or_404(Scenario, id=sc_id) # TODO : add rule in the same view create_rule_div = create_rule_view(request, id, sc_id) print("content", create_rule_div) context = { 'scenario': object, 'create_rule_div': create_rule_div } return render(request, "scenario/detail_scenario.html", context) This is rule_create.html: {% block content %} <form method="POST"> {% csrf_token %} <h2>Create Rule</h2> {{ rule.name}} {{ input.patterns }} {{ answer.text }} <input type="submit" value="Save Rule"/> </form> {% endblock %} This is detail_senario.html: {% block content %} <h2>Scenario {{ scenario.id }}</h2> <p>Scenario for : {{ scenario.chatbot_id }}</p> <p>Name: {{ scenario.name }}</p> <p>Description: … -
Django admin send email for new user registration
In my project i'm trying to send an email after new user creation. I try like this in my models.py: @receiver(post_save,sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: first_name = instance.first_name last_name = instance.last_name email = instance.email context = { 'news': 'Your testdemo account', 'user': instance.username, 'pass': "test" } html_content = render_to_string('email_demo.html', context) message=EmailMessage(subject='Test Demo Account Registration',body=html_content,to=[email]) message.content_subtype='html' message.send() If i run my user creation proces nothing appen, but if i remove the if created: statement all works ok, execpt for the fact that email was send also when user logged in (i would that email was send just when user is register first time, not when he logged in) So many thanks in advance -
Form Previous to stripe script needs to be fully filled before being able to pay
I have a form previous to a stripe payment button(which is created by a script) that i need people to actually fill properly before paying. this is the script to gray out payment until form is filled (problem it is only for text inputs) <script> $('.stripe-button-el').attr('disabled', true); $('input:text').keyup(function () { var disable = false; $('input:text').each(function () { if ($(this).val() == "") { disable = true; } }); $('.stripe-button-el').prop('disabled', disable); }); </script> the form goes like this <div class="container" style="padding:40px 0px;text-align: center;"> <form method="POST" action="{% url 'charge' %}" id="patientForm" data-times-url="{% url 'ajax_load_time_slots' %}"> {% csrf_token %} <p><label for="id_patient_name">{% trans "Patient Name:"%}</label> <input type="text" name="patient_name" maxlength="60" id="id_patient_name"></p> <p><label for="id_phone_number">{% trans "Phone Number:"%}</label> <input type="tel" name="phone_number" id="id_phone_number"></p> <p><label for="id_patient_country">{% trans "Country:"%}</label> <input type="text" name="patient_country" id="id_patient_country"></p> <p><label for="id_email">{% trans "Email:"%}</label> <input type="email" name="email" maxlength="254" id="id_email"></p> <p><label for="id_event_date">{% trans "Event Date:"%}</label> <input type="date" name="event_date" id="id_event_date"></p> <p><label for="id_start">{% trans "Time:"%}</label> <select class="specialselect" name="start" required id="id_start"> <option value="" selected>---------</option> </select></p> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_KPSQTmUOl1DLP2eMc7zlvcnS" data-description="Buying a 30mn Skype Session" data-amount="3000" data-locale="auto"></script> </form> </div> the code work as for graying out the button, BUT, even with everything filled the button doesnt become available <div class="container" style="padding:40px 0px;text-align: center;"> <form method="POST" action="{% url 'charge' %}" id="patientForm" data-times-url="{% url 'ajax_load_time_slots' … -
ModuleNotFoundError: No module named 'channels' even after rechecking that i have installed the package
there is an issue with my packages, i have installed django channels(just channels) using pip install channels command and when i tried to run server command i just got an error sayinh the module not found but when i run the command pip list | grep channels there are two modules installed channels 2.1.6 channels-redis 2.3.3 i dont know the reason behind the error can somone help me figure out if i have done anything wrong i have added them in insalled app section of settings.py -
Override instance data in a ModelForm
I have a form which includes nested forms for polymorphic related objects: class MyForm(forms.ModelForm): class Meta: model = MyModel exclude = [] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) if self.instance: self.related_forms = [] # our form happens to include nested forms for related objects for related in instance.related_models.all(): # our related_models are polymorphic form_class = modelform_factory(related.__class__, form=RelatedModelForm, exclude=[]) form = form_class(instance=related.__class__.objects.filter(mymodel=instance)[0]) self.related_forms.append(form) I am trying to implement a way to provide initial data to preload the form with a different MyModel instance. Note that I am not trying to define self.initial, this is different. If such a secondary instance is passed to the form constructor, the form and related forms should take its values instead of self.instance, but the form and related forms should remain bound to their original self.instance so that the appropriate entries are updated. How can I do this? Feeding those values to self.initial is not the way to go because all this does is fill in empty values. Passing a different instance to the forms when instantiated is no good either. We would be then filling in the values we want but the form would now be bound to the wrong objects. -
Django Modelform password validate iteration
I am trying to write Django Modelform to prompt user to register an account with a robust password (contains Uppercase, lowercase, digits and special chars). If the multiple conditions for a password are not met, it will raise multiple field level validation error. For example, if I enter a password "shafin071", the Validation errors should say - The password must contain at least 1 uppercase letter, A-Z. - The password must contain at least 1 symbol But right now I'm not getting the 2nd validation error. 1) Can you please help me find a better iteration that will check all the conditions? 2) How can I use clean() to throw a field level validation error instead of form level? I'm fairly new to coding so some explanation will be appreciated. Thank you! forms.py: import re from django import forms from django.utils.translation import gettext_lazy as _ from .models import Students class StudentRegisterForm(forms.ModelForm): class Meta: model = Students fields = [ 'firstName', 'lastName', 'email', 'password', 'password2', 'street', 'apt', 'city', 'state', 'zipcode', ] labels = { 'firstName': _('First Name'), 'lastName': _('Last Name'), 'password2': _('Confirm Password'), 'Apt': _('Apt/House'), 'zipcode': _('Zip Code'), } widgets = { 'password': forms.PasswordInput, 'password2': forms.PasswordInput } help_texts = { 'password': …