Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying both Django and MySql Server to one CentOS 7 Server Conflicts
I'm trying to deploy a Django App with MySQL server to a CentOS 7 server, but I'm having issue with installing MySQL server and mysqlclient on the same server. I first had MariaDB installed and running fine, but when I tried to install mysqlclient, I get conflict errors. I had to remove the MariaDB server to install the mysqlclient, but then when I tried to install MariaDB server back, I got the same error messages. Can this be done, or should I set them up separately? Thanks! # sudo yum install mysql-server ... --> Finished Dependency Resolution Error: mariadb101u-libs conflicts with MariaDB-compat-10.2.14-1.el7.centos.x86_64 Error: mariadb101u-common conflicts with MariaDB-compat-10.2.14-1.el7.centos.x86_64 Error: mariadb101u-common conflicts with MariaDB-common-10.2.14-1.el7.centos.x86_64 Error: mariadb101u-config conflicts with MariaDB-common-10.2.14-1.el7.centos.x86_64 Error: mariadb101u-config conflicts with MariaDB-compat-10.2.14-1.el7.centos.x86_64 You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigest -
Looping insert data to database with django
can insert loop data into django model?.. here my code. on view.py class EmpCreateView(CreateView): fields = () model = models.Employee def form_valid(self, form): self.object = form.save(commit=False) loopdo = 5 while loopdo > 0: self.object.name = "work?" self.object.no = loopdo self.object.save() loopdo -= 1 return super(ModelFormMixin, self).form_valid(form) it's only insert 1 data. -
too many values to unpack (expected 2) while extending django user model
Now I know that there have been various questions like this, but I looked at all of them but couldnt figure out what was going wrong. Im extending User model of django admin and in the final processes Im getting this error. Im unable to understand what actually triggered the event. This is the view portion user = UserRegister(request.POST) userprofile= UserProfileCreate(request.POST) if user.is_valid() and userprofile.is_valid(): print('valid') user.save() I have passed 2 forms to the template as it is seen. The 2 forms.py are: class UserRegister(forms.Form): first_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'First Name'})) last_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Last Name'})) username = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Username'})) email = forms.EmailField( required=True, widget=forms.widgets.EmailInput(attrs={'placeholder': 'Email'})) password =forms.CharField(required=True, widget=forms.widgets.PasswordInput()) confirm_password =forms.CharField(required=True, widget=forms.widgets.PasswordInput()) class Meta: model=User fields=['first_name','last_name','username','email','password','confirm_password'] def clean_username(self): username = self.cleaned_data.get('username') if username and User.objects.filter(username=username).count(): print(User.objects.filter(username).first_name) e = forms.ValidationError('This username is already in use. Please choose a different username.') raise e return username def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): print(User.objects.filter(username).first_name) e = forms.ValidationError('This email address is already in use. Please supply a different email address.') raise e return email def clean_confirm_password(self): password = self.cleaned_data.get("password") confirm_password = self.cleaned_data.get("confirm_password") if password != confirm_password: print(password) print(confirm_password) raise forms.ValidationError( "Password and password confirmation does not match" ) return password … -
Prepopulate ModelMultipleChoiceField Django
I am creating a website that allows users to follow stocks and see articles based on those stocks. Upon registration the user follows Stocks for the first time. After this I would like them to be able to view a page that shows all Stocks and which ones they follow. How can I prepopulate a ModelMultipleChoiceField? models.py: class Stock(models.Model): name = models.CharField(max_length = 50) ticker = models.CharField(max_length = 50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed_stocks = models.ManyToManyField(Stock, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views.py: def test(request): if request.method == "POST": form = StockFollowForm(request.POST) if form.is_valid(): request.user.profile.followed_stocks = list(form.cleaned_data.get('stocks_selected')) request.user.profile.save() return redirect('index') else: form = StockFollowForm() #how do I prepopulate this if there are already followed Stock objects return render(request, 'core/test.html',{'form': form}) template: <div class = "container"> <h2 class = "text-center">Register</h2> <form method = 'post'> {% csrf_token %} {{ form }} <div class = "text-center"> <br/> <button class="btn btn-primary" type = 'submit'>Follow/Unfollow Stocks</button> </div> </form> </div> forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Stock from django.forms import ModelMultipleChoiceField class ProfileRegistrationForm(UserCreationForm): class Meta: model = User fields = … -
how to use raw sql in django
def home(request,*args,**kwargs): blog = models.Blog.objects.filter(site = kwargs['site']).select_related('user').first() tag_list = blog.tag.all() article_list = blog.article_set.order_by("-nid").all() date_list = blog.article_set.raw('select nid, count(nid) as num,strftime("%Y-%m",create_time) as ctime from repository_article group by strftime("%Y-%m",create_time)') category_list = blog.category_set.all() return render(request, 'home.html', {'blog':blog,'tag_list':tag_list,'category_list':category_list,'article_list':article_list,'date_list':date_list}) I try to use raw sql in django but what i import is pymysql,so it seems i can not use the raw method.What should i do to solve this problem,my english is poor,sorry guys,and thank you very much -
get() missing 1 required positional argument: 'email'
i have an app which has following model from django.db import models class Saved(models.Model): email = models.CharField(max_length=200, blank=False, default='') ad_id = models.IntegerField(blank=False) def save(self, *args, **kwargs): super(Saved, self).save(*args, **kwargs) following is the serializers.py from rest_framework import serializers from saved.models import Saved class SavedSerializer(serializers.ModelSerializer): class Meta: model = Saved fields = ('email', 'ad_id') and here is the view.py from django.db.models import Q from rest_framework.response import Response from rest_framework.views import APIView from saved.models import Saved from saved.serializers import SavedSerializer from rest_framework import status class SavedView(APIView): def get_queryset(self, email): saved = Saved.objects.all() if email: saved = deployed_contracts.filter( Q(email__iexact=email) ) return saved def get(self, request, email, format=None): service_providers = self.get_queryset(email) serializer = SavedSerializer(service_providers, many=True) return Response(data=serializer.data) def post(self, request, format=None): serializer = SavedSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) in my app's urls.py i have following code from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from saved import views router = DefaultRouter() urlpatterns = [ url(r'^(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', views.SavedView.as_view()), url(r'^', views.SavedView.as_view()) ] and in project's urls i have following piece of code rom django.contrib import admin from django.urls import path from django.conf.urls import include, url urlpatterns = [ path('admin/', admin.site.urls), url(r'^saved', include('saved.urls')) ] but api is giving following error TypeError at /saved/shoaib2@gmail.com/ … -
How do I build this web application? [on hold]
I'll begin by saying that I'm a big noob and appreciate any guidance provided in response to this question. I have a small business with 2 employees. I want to build a web application where my employees can login and either add customer contact information or retrieve contact information. I played around with Zoho Creator (no laughter, please) and decided that I'd rather create and host this myself. Im familiar with html and CSS. Im also familiar with SQL. So what I need is to authenticate my users, present them with a page that allows them to query my database and view or insert new records. Ive already created a database and contacts table in MYSQL on my web host. I've been trying to make sense of all these web frameworks (Django, Laravel, Joomla) and not sure what direction to go in. Im looking to learn-while-doing but not sure what I need to learn to move forward Long term I would love to build on this to have a portal for my employees to do more than add and retrieve customer info. Thank you in advance for your responses. -
Django: loading alluath template with form to div loads additional things
I've one site website with simple account managing. I have a few divs to which I load some other things (other divs, django forms and stuff like that) using jQuery load() function and everything works perfectly fine. I want to use django allauth app for account managing and right now I'm trying to add functionality to load password_change template to some div. This password_change.html template looks like this: <form method="POST" action="accounts/password/change/" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> and here is template to which I'm trying to load it <div> <div> <div onclick="$('#item').load('accounts/password/change');">Change password</button> </div> <div id="item"></div> </div> After clik on button load performes but instead of password change form I see some dictionary: {"form": {"fields": {"oldpassword": {"widget": {"attrs": {"placeholder": "Current Password"}}, "value": null, "errors": [], "label": "Current Password", "help_text": ""}, "password1": {"widget": {"attrs": {"placeholder": "New Password"}}, "value": null, "errors": [], "label": "New Password", "help_text": ""}, "password2": {"widget": {"attrs": {"placeholder": "New Password (again)"}}, "value": null, "errors": [], "label": "New Password (again)", "help_text": ""}}, "field_order": ["oldpassword", "password1", "password2"], "errors": []}, "html": "\n \n Current Password: \"Current \n New password: \"New \n New password (again): \"New \n \"Submit\" \n "} I presume that it's pure Django object … -
Django - Is this good practice?
I need a website that contains the following pages: Index - Completely static, just informational Register - Register an account. I think django-user-accounts provides this functionality? Login - Login to a registered account. UserCP - Page that the user can do an action when logged in. Index (index.html) will be 100% static with links to the register, login, pages. Register/Login/UserCP will all be webapps written in Django. Would it be "good practice" to serve index.html using Django? The example I found used this code in the urls.py file: path('', TemplateView.as_view(template_name='index.html')), -
Django hash password
I use django.contrib.auth My problem: login wont work because the password is saved in clear, when I go in admin or in the shell I can see the password in clear text. If I manually use User.set_password() in the shell, then I can login. So, why the password is saved in clear and not automatically hashed? I extend the default User to add attributes. from django.db import models from django.contrib.auth.models import User class Profil(User): user = models.OneToOneField(User, on_delete=models.CASCADE, parent_link=True) postal_code = models.CharField(max_length=255) facebook_profil = models.URLField(max_length=255) make = models.CharField(max_length=255) model = models.CharField(max_length=255) year = models.CharField(max_length=255) photo = models.ImageField(upload_to="") def __str__(self): return self.user.username Then I have a register and a login forms : from django import forms from members.models import Profil class RegisterForm(forms.ModelForm): class Meta: model = Profil exclude = ("is_staff", "groups", "is_active", "is_superuser", "user_permissions", "last_login", "date_joined") fields = ["username", "password", "first_name", "last_name", "email", "postal_code", "facebook_profil", "make", "model", "year", "photo"] class LoginForm(forms.Form): username = forms.CharField(label="Nom d'utilisateur", max_length=30) password = forms.CharField(label="Mot de passe", widget=forms.PasswordInput) And finally I have a CreateView and a LoginView to register and login the user : from django.shortcuts import render from django.views.generic import CreateView from .models import Profil from .forms import RegisterForm, LoginForm from django.urls import reverse_lazy from django.contrib.auth.views … -
No permissions when running a command inside Elastic Beanstalk container
Hi I'm using elastic beanstalk to deploy a django application. The problem is I need to run a service inside de container. I'm trying to start the service manually running the command. But when I run de command it says I don't have permissions to run it inside the app folder. I'm able to run it outside the app folder but the command needs to be run inside the app folder because it is going to create some files. -
Django 2.0, First Level Class View, AttributeError: 'str' object has no attribute 'values'
I have created a generic view and serializer in Django 2.0, so that I don't have to repeat my self, creating CRUD views or serializers. My views.py file of my API app from rest_framework import generics, mixins from rest_framework.serializers import ModelSerializer class StandardListMixinCreateApiView(mixins.CreateModelMixin, generics.ListAPIView): def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class StandardRudApiView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'pk' This function sets The serializer.Meta.model of each enabled model. The `cls parameter is one of the StandardApiViews. def get_adapted_class(cls, model_class, serializer_fields='__all__'): class AdaptedSerializer(ModelSerializer): class Meta: model = model_class fields = serializer_fields class AdaptedView(cls): model = model_class.__name__ queryset = model_class.objects.all() serializer_class = AdaptedSerializer return AdaptedView My urls.py from django.urls import re_path from .views import * from django.contrib.auth.models import Group, Permission from .models import * app_name = "api" The models for which CRUD views get generated. ENABLEDMODELS = [ Address, Group, Permission, Customer, Employee, Commission, BugReport, FeatureRequest, ] APILISTVIEWS = [get_adapted_class( StandardListMixinCreateApiView, model) for model in ENABLEDMODELS] APIRUDVIEWS = [get_adapted_class( StandardRudApiView, model) for model in ENABLEDMODELS] Adds an url route for each created ListView to the urlpatterns # List, create views urlpatterns = [re_path( f'^(?i){class_view.model}/', class_view.as_view(), name=f'{class_view.model}-list') for class_view in APILISTVIEWS] # Retrive, update, delete views urlpatterns += [re_path( f'^(?i){class_view.model}/' + r'(?P<pk>\d+)', class_view.as_view(), name=f'{class_view.model}-rud') … -
nginx 502 error unix path no such file or directory
I am nearly finished publishing my web server, but when I search for the domain name, I get a 502 error, bad request. When looking in the nginx error logs, I get this: connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream The problem is that the path unix is taking, is not correct, and I want to change it to: home/daniel/myproject/myproject.sock Basically I haven't find a solution for this problem while scouring the internet, and I will be very grateful for any help regarding this issue. -
Retrieving HTML form data and storing it in Python
Believe me I have looked everywhere before asking such a generic question without any code: I already have some HTML forms that take user data. Do I need to setup my entire website with Flask or Django simply to get the data entries which I can then manipulate in Python? Server scripting is waaaayy over my head. My understanding of t'internet goes like this: Someone has computer. Uses said computer to connect to a domain /IP. They do a GET request through some wires and witchcraft. And essentially 'grab' the requested page from the server (or if generic domain, the server directs them to index.html). Their browser turns code into images and they fill in some boxes. They click send. This submits a POST request to the website server. All of this happens without Python or PHP. To 'store' the submitted data, something needs to intercept the message on the server. This can be either Python or PHP. (I at least know some Python). There is a tag in HTML that includes action="". Somehow this what ? Runs a python script? How? What type of Python? My server has 2.6 on it. Where does flask come in? Or Django? Does … -
Django - Update data in a model that has a onetoone relationship with user
I have a user model and a model that has a 1-to-1 relationship with that user. I want to update the information in the model (Person), but when I hit submit, the page 'completes successfully; e.g. executes the get_success_url, but the data isn't updated in the database. I even added a print statement print(vars(self.request.user.person)) to the view, but even the output doesn't show that the changes made on the form. How do I get the onetoone model to update it's information? Thanks! Models.py class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) price = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) travel_flag = models.BooleanField(blank=True, default = False) forms.py class Meta: model = Person fields = ['user', 'travel_flag','price'] views.py class UserProfileUpdateView(LoginRequiredMixin, UpdateView): form_class = UserProfileChangeForm template_name = 'accounts/profile-update-view.html' def get_object(self): print(vars(self.request.user.person)) return self.request.user def get_context_data(self, *args, **kwargs): context = super(UserProfileUpdateView, self).get_context_data(*args, **kwargs) context['title'] = 'Update Your Profile' return context def get_success_url(self): return reverse("account:home") html page <form method='POST' action='{% if action_url %}{{ action_url }}{% endif %}'> {% csrf_token %} <div class="form-group"> <label for="id_price" class="active">Price: $</label> <input id="id_price" type="number" name="currency" min="0" max="99999" step="0.01" size=4 value="{{ user.person.price }}"> </div> <div class="form-check"> <input id="id_travel" type="checkbox" name="travel" value="{{ user.person.travel_flag }}" > <label for="id_travel" class="active"></label> </div> <button type="submit" class="btn btn-primary">Submit</button> -
How to Implement this Model Method in a Model Manager, or Other Alternative
I have this two simplified models, part of a Inventory App: class Item(models.Model): name = models.Charfield() unity = models.Charfield() audit_interval = models.PositiveIntegerField(help_text='Seconds Between Audits') def should_audit(self): last_audit = Quantity.objects.filter(item=self).last() now = timezone.now() if last_audit: delta = now - last_audit.timestamp if delta.seconds > self.audit_interval: return True else: if self.in_stock_total() < 0: return True else: return False else: return True class Quantity(models.Model): item = models.ForeignKey(Item) timestamp = models.DateTimeField(auto_now_add=True) value = models.PositiveIntegerField() user = models.ForeignKey(User) So, with this, each Item could be multiple Quanityt records, each one showing by who and when the audit was performed. Now, I want to be able to filter the items based on the fact that should_audit() is True. I was thinking in using a Model Manager but the fact that the should_audit() method is based in information of the same row (audit_interval) is forbidding me to do this, or at least I don't known how. I always picture Model Manager as a tool to codify one or more filters in your application. Is this view wrong? I know I could use list comprehension, but I do not like very much of this method because of the potential impact in performance. Please also note that are other facts … -
Custom admin form error "need more than 1 value to unpack"
I have been adapting this article How to Add Custom Action Buttons to Django Admin to my particular circumstance and things are working pretty well except for this one strange error I am getting. In my forms.py I have defined class DenyForm: (Note the request parameter in form_action is not the usual API request. I have a model class Request.) What should form_action be returning? class DenyForm(ApproveOrDenyForm): def form_action(self, request, admin_approver ): print "forms DenyForm Called." justification = self.cleaned_data['justification'] request.admin_deny(admin_approver=admin_approver,justification=justification) return [request] #return request.admin_deny(admin_approver=admin_approver,justification=justification) This results in a message of “‘Please correct the errors below.’ need more than 1 value to unpack”. I have tried different endings to my form_action method. If my last line is: return request I get “‘Please correct the errors below.’ ‘Request’ object is not iterable”. If the last line is: return request.admin_deny(admin_approver=admin_approver,justification=justification) I get this … “‘Please correct the errors below.’ ‘NoneType’ object is not iterable”. That is because admin_deny() does not return anything. What should form_action be returning? -
None type object not iterable error
I am creating a website that allows users to follow stocks and see articles based on those stocks. When I try to save the stocks they follow to the database I get the following error: Error: "request.user.profile.followed_stocks = list(form.cleaned_data.get('stocks_selected')) TypeError: 'NoneType' object is not iterable" models.py: class Stock(models.Model): name = models.CharField(max_length = 50) ticker = models.CharField(max_length = 50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed_stocks = models.ManyToManyField(Stock, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views.py: def test(request): if request.method == "POST": form = StockFollowForm(request.POST) if form.is_valid(): request.user.profile.followed_stocks = list(form.cleaned_data.get('stocks_selected')) request.user.profile.save() return redirect('index') else: form = StockFollowForm() return render(request, 'core/test.html',{'form': form}) template: <div class = "container"> <h2 class = "text-center">Register</h2> <form method = 'post'> {% csrf_token %} {{ form }} <div class = "text-center"> <br/> <button class="btn btn-primary" type = 'submit'>Login</button> </div> </form> </div> forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Coin from django.forms import ModelMultipleChoiceField class ProfileRegistrationForm(UserCreationForm): class Meta: model = User fields = ('username', 'password1', 'password2', 'email', 'first_name' ,'last_name') class CoinFollowForm(forms.Form): coins = forms.ModelMultipleChoiceField(required =False, widget=forms.CheckboxSelectMultiple, queryset=Coin.objects.all()) Thanks in advance! -
DeleteView with 2 arguements post and user
I have a delete view with 2 conditions post and user The user requirement is fulfilled by self.object.user = self.request.user and post requirement is fulfilled by slug = self.kwargs['slug']. Are my views correct. I am new to python please forgive any silly mistakes Views.py class ProofDelete(LoginRequiredMixin, DeleteView): model = Proof def delete(self, *args, **kwargs): return super().delete(*args, **kwargs) def get_success_url(self, *args, **kwargs): slug = self.kwargs['slug'] print(slug) obj = get_object_or_404(Post, slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.made.all(): obj.made.remove(user) else: obj.made.add(user) return url_ models.py User = get_user_model() class Proof(models.Model): user = models.ForeignKey(User, related_name='proofmade') post = models.ForeignKey(Post, related_name='proofmade') made_at = models.DateTimeField(auto_now=True) image_of_task= models.ImageField() proof_you_made_it = models.ImageField() suggestions = models.TextField(max_length=1000) def __str__(self): return self.post.title urls.py app_name = 'proof' urlpatterns = [ url(r'^new_proof/(?P<slug>[-\w]+)/$', views.ProofCreate.as_view(), name='new_proof'), I have tried 3 different urls for delete none of them work, The create Url works thanks to the "Alasdair" below are the 3 url patterns I have tried url(r'^proof_delete/(?P<pk>\d+)/$', views.ProofDelete.as_view(), url(r'^proof_delete/(?P<slug>[-\w]+)/$', views.ProofDelete.as_view(), url(r'^proof_delete/(?P<slug>[-\w]+)/(?P<pk>\d+)/$', views.ProofDelete.as_view(), -
Combining FormView and DetailView doesn't show form on the page
I have a DetailView, in which I show contents of a post and as well I wanted to add comments functionality to that view. I found 2 ways to do it: combine a DetailView and FormView or make a custom view with mixins. Since I am new to Djanfgo, I went on the 1st way, guided by this answer: Django combine DetailView and FormView but i have only a submit button and no fields to fill on a page. Here is a necessary code: #urls.py from . import views app_name = 'bankofideas' urlpatterns = [ path('<int:pk>/', views.DetailView.as_view(), name='idea'), path('<int:idea_id>/vote', views.vote, name='vote'), path('<formview', views.MyFormView.as_view(), name='myform') ] #views.py class DetailView(generic.DetailView): model = Idea template_name = 'bankofideas/detail.html' context_object_name = 'latest_question_list' def get_queryset(self): return Idea.objects.filter(pub_date__lte=timezone.now()) def get_context_data(self, **kwargs): # передача формы context = super(DetailView, self).get_context_data(**kwargs) context['comment_form'] = CommentForm#(initial={'post': self.object.pk}) return context class MyFormView(generic.FormView): template_name = 'bankofideas/detail.html' form_class = CommentForm success_url = 'bankofideas:home' def get_success_url(self): post = self.request.POST['post'] Comment.objects.create() return '/' def form_valid(self, form): return super().form_valid(form) #models.py class Idea(models.Model): main_text = models.CharField(max_length=9001, default='') likes = models.IntegerField(default=0) pub_date = models.DateTimeField('date published', default=timezone.now) def __str__(self): return self.main_text def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.pub_date = timezone.now() #self.modified = timezone.now() return … -
Django view return value with AJAX
I am working with Django and AJAX, I have a template where people can select an option and then click a submit button. The button fires an Ajax function that sends the data to my view where it is processed and should return a value back to the template. The issue is when the post goes through, it hits the view, and nothing is returned to the template, I am not sure if this is because the view isn't getting any data, but it isn't firing any of my conditional statements, so it acts like its working but doesn't return anything. My HTML form: <form method="POST" id="buy_form" name="buy_form" action="{% url 'manage:buy' %}"> {% csrf_token %} <div class="buy_top_section"> <div class="width"> <div class="spacing"> <h3 class="sell_title">How much do you want to sell?</h3> <input type="text" id="amount" class="buy_input_top" maxlength="10" name="amount" type="number" required> <select id="selected" class="buy_selection" name="wanted"> <option value="generate_b">BTC</option> <option value="generate_e">ETH</option> <option value="generate_l">LTC</option> </select> </div> <span class="float_clear"></span> <button id='generate' type="submit" value="currency_details" class="custom_button"l">Generate </button> </div> </div> </form> <!-- What needs to be returned from thew view --> <h1>{{ address }}</h1> My AJAX $(document).on('submit', '#buy_form', function (e) { e.preventDefault() $.ajax({ type: 'POST', url:'/manage/buy/', data:{ currency:$('selected').val(), amount:$('#amount').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function (){ } }) }); My Django View def … -
Send data from pyqt5 to django, with authentication process
I'm doing an GUI program to automaticly send desktop data to my website, which has a standard user authentication view working. How can I send the data with the user/password appended to it safely? I'm thinking on sending it as JSON {"data": data, "username": username, "password": salted_hashed_password}, but then how can I make the server receive the data only if the login is authorized? How can I check if the salted and hashed password is correct? I think sending passwords as plain text could be a vulnerability to the users privacy. -
Checking is_valid() on a specific field
I'm attempting to check the 'image' field on my form to see if it's valid. Within my view, I've got the following code: if form.is_valid(): #some stuff else: if form.image.is_valid(): pass else: form.image = None I have a custom validator that causes the form to not validate if the image that the user attempts to upload is > 5MB. When I upload an image > 5MB, I get the following error: 'EditUserProfileForm' object has no attribute 'image' This form definitively has an 'image' field on it. It's a model form and the model also has an 'image' field. The user can successfully upload a photo if its less than 5MB, so its not anything else that's broken. Any ideas? -
Block access to Django folder
I am running a Django application and I just discovered that anybody could access my Django files if they knew the proper address. Including my settings.py file with sensitive information. How can I block access to such files so that they can't be accessed by random people without a server access? -
.sock file not appearing in project directory with gunicorn
I am trying to set up gunicorn for my web server, and I am currently following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#create-a-gunicorn-systemd-service-file The problem is that gunicorn has not generated a myproject.sock file in the directory of my project. My configuration in this file: /etc/systemd/system/gunicorn.service, looks like this: [Unit] Description=gunicorn daemon After=network.target [Service] User=daniel Group=www-data WorkingDirectory=/home/daniel/myproject ExecStart=/home/daniel/myproject/myproject_venv/bin/python3 home/daniel/myproject/myproject_venv/bin/gunicorn --workers 3 -b :8000 myproject.wsgi:application [Install] WantedBy=multi-user.target I am using Django from Digital Ocean for my web server, so right at the very start, the server came with files and directories such as django/django_project/django_project. But instead of using the already-made files, I created a new project with new directories (Just as the tutorial said). When looking at the gunicorn error logs, with sudo journalctl -u gunicorn, at the top, it says: Listening at: unix:/home/django/gunicorn.socket (1915) As previously stated above, I made a new project with different directories than the ones with django, so I am looking for a way to change where gunicorn is listening to. Specifically, I want it to listen at home/daniel/myproject/myproject.sock. Unfortunately, myproject.sock doesn't exist for some reason. my project files are owned by a sudo user and group, so that unicorn has access. The WorkingDirectory should be correct. I would appreciate …