Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get error : id() takes exactly one argument (0 given) ,save with foreign key
So i have problem about to save data with foreign key, here my models.py class Connect(models.Model): username = models.CharField(max_length=255) password = models.CharField(max_length=255,null=True, blank=True) conft = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return unicode(self.username) class Ip(models.Model): class Meta: db_table = 'autonet_ip' connect_id = models.ForeignKey(Connect, on_delete=models.CASCADE) ipaddr = models.CharField(max_length=255) def __str__ (self): return self.ipaddr my forms.py class NacmForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput,required = False) class Meta: model = Connect fields = ['username', 'password','conft'] labels = {'conft':_('Config'),} class IpForm(ModelForm): class Meta: model = Ip fields = ['ipaddr'] labels = {'ipaddr':_('IP address'),} IpFormset = formset_factory(IpForm, extra=1) my views.py def konfig(request): ip_list = [] status = '' value_bak = 1 if request.method == 'POST': formm = NacmForm(request.POST or None) ipform = IpFormset(request.POST) upform = UploadForm(request.POST,request.FILES) userValue = formm['username'].value() passValue = formm['password'].value() confValue = formm['conft'].value() usernamef = get_object_or_404(Connect, pk=id) if ipform.is_valid(): for form in ipform: ipaddr = form.cleaned_data.get('ipaddr') //.... some code ...// simpanIp = form.save(commit=False) simpanIp.connect_id = usernamef simpanIp.save() simpanForm.save() return HttpResponseRedirect('/konfig') else: formm = NacmForm() ipform = IpFormset() return render(request, 'konfig.html', {'form': formm, 'logins': Connect.objects.all(), 'ipform': ipform, 'status': status }) then when i input all data and click submit to save, i got an error "id() takes exactly one argument (0 given) ". I just … -
How to set Django allowed_hosts?
Just don’t understand, in Django documents and other articles, allowed_hosts is not recommended to be [‘*’] for security reasons. But a website should be open to the whole internet, what value should it be? -
How to resend confirmation email in Django from a React front end, using allauth and rest-auth
I'm using Django 2.0.10 with rest framework, rest-auth and allauth, with a React front end. Rest-auth provides login and logout functionality using JWT token authentication, but I can't work out how to allow the user to request a resend of the verification email. I want a user to be able to log in and press a button saying "Resend confirmation email". If for example they accidentally deleted the email, they need to be able to request another. I've seen posts suggesting that you can use send_email_confirmation from allauth, but this expects a CSRF token which would be generated by a template. Here's my code: urls.py from users.views import EmailConfirmation urlpatterns = [ ... url(r'^/sendconfirmationemail/', EmailConfirmation.as_view(), name='send-email-confirmation') ] views.py from rest_framework.views import APIView class EmailConfirmation(APIView): def post(self): send_email_confirmation(user=self.request.user) When I post to the endpoint '/api/v1/rest-auth/sendconfirmationemail/', I get an error Forbidden: <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for &#39;same-origin&#39; requests.</p> Any idea how I can request … -
Request is not getting into views, but its shows the corret url
Form is loaded in html page but when i click submit button,it shows nothing(No HttpResponse which i used in views). But it show url(http://localhost:8000/datainsert )as i described in urls.py. Please point out what's wrong in my code. forms.py from django import forms from .models import Test class TestForm(forms.ModelForm): class Meta: model = Test fields = '__all__' views.py def datainsert(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() return HttpResponse('Saved') return HttpResponse('Not saved') urls.py from django.conf.urls import url from . import views from .views import index, datainsert, testing urlpatterns = [ url(r'^', views.index, name='index'), url(r'^datainsert', views.datainsert, name='datainsert'), ] index.html <html> <head> <title>My Web</title> </head> <body> <form action="{% url 'myapp:datainsert' %}" method="POST"> {% csrf_token %} {{form}} <button type="submit">Submit</button> </form> </body> </html> -
Permissions not working using django-gaurdian for djangorestframework
I am trying to add object level permission to my django REST project using django-guardian, but I am getting http://127.0.0.1:8000/api/v1/tasks/ HTTP 403 Forbidden Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "You do not have permission to perform this action." } The user joe is logged in. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'guardian', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'task.apps.TaskConfig', ] models.py: class Task(models.Model): summary = models.CharField(max_length=32) content = models.TextField() reported_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( ('view_task', 'View task'), ) serializers.py: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' permissions.py: class CustomObjectPermissions(permissions.DjangoObjectPermissions): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } filters.py: class DjangoObjectPermissionsFilter(BaseFilterBackend): perm_format = '%(app_label)s.view_%(model_name)s' shortcut_kwargs = { 'accept_global_perms': False, } def __init__(self): assert 'guardian' in settings.INSTALLED_APPS, ( 'Using DjangoObjectPermissionsFilter, ' 'but django-guardian is not installed.') def filter_queryset(self, request, queryset, view): from guardian.shortcuts import get_objects_for_user user = request.user permission = self.perm_format % { 'app_label': queryset.model._meta.app_label, 'model_name': queryset.model._meta.model_name, } return get_objects_for_user( user, permission, queryset, **self.shortcut_kwargs) views.py: class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer permission_classes = (CustomObjectPermissions,) filter_backends = (DjangoObjectPermissionsFilter,) urls.py: router = DefaultRouter() router.register('tasks', TaskViewSet, … -
removed all the apps, flush db still getting this error
python manage.py makemigrations (not detecting any changes.) when i am typing python manage.py migrate so getting this error. Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying auth.0001_initial...Traceback (most recent call last): File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 296, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: table "auth_permission" already exists used all the solutions available on this web as well as on other web. but unable to solve it. i have removed all my apps, flushed & reset db. also removed migration folder (so it will not detect previous apps data) -
python setup in cpanel File (/usr/bin/virtualenv): [Errno 2] No such file or directory
when i trying to setup python on my cpanel i get this error (File (/usr/bin/virtualenv): [Errno 2] No such file or directory) enter image description here and my host provider support python -
502 bad gateway after redirecting to https django
I've been trying to encrypt my website with http, ut when redirecting I get 502 bad gateaway, I use Digital Ocean with nginx on Ubuntu 14 and django: Here is my server config: upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { # listen 80 default_server; # listen [::]:80 default_server ipv6only=on; listen 443 ssl; server_name = programmationetia.com; ssl_certificate /etc/letsencrypt/live/programmationetia.com/fullchain.pem ; ssl_certificate_key /etc/letsencrypt/live/programmationetia.com/privkey.pem; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/django_project/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass https://app_server; } } server { listen 80; server_name programmationetia.com; return 301 https://$server_name$request_uri; } I followed Sentex tutorial on encrypting with ssl. Thank you for helping -
Invalid format string at _generate_jwt_token
this is the tutorial I'm following, the link https://thinkster.io/tutorials/django-json-api/authentication As the title says, I'm getting this error "Invalid format string" at this line: 'exp': int(dt.strftime('%s')) of _generate_jwt_token. I looked at the documentation of strftime and there is no such format '%s' there is a uppercase S ('%S'), I changed the format to the uppercase S, but I'm getting an error down the road at trying to decode the Authorization Token where i get the following error {"user": {"detail": "Invalid authentication. Could not decode token."}} If I leave the lowercase s I get the "Invalid format string" error. (authentication/backends.py) def _authenticate_credentials(self, request, token): """ Try to authenticate the given credentials. If authentication is successful, return the user and token. If not, throw an error. """ try: payload = jwt.decode(token, settings.SECRET_KEY) except: msg = 'Invalid authentication. Could not decode token.' raise exceptions.AuthenticationFailed(msg) (authentication/models.py) def _generate_jwt_token(self): """ Generates a JSON Web Token that stores this user's ID and has an expiry date set to 60 days into the future. """ dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') I expect the following token "Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MiwiZXhwIjo0fQ.TWICRQ6BgjWMXFMizjNAXgZ9T2xFnpGiQQuhRKtjckw" to return a user. -
{ "detail": "Method \"GET\" not allowed." }
So the problem i have already mentioned. I am a beginner, i might be doing some silly mistakes. So humble request to you guys to address my mistake and help me to complete my project. Thanks you all in advance. setting.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3600), } this is the setting.py file and here i mention the required file view.py class LoginViewSet(viewsets.ViewSet): """ Check email and password and return auth token. """ serializer_class = AuthTokenSerializer authentication_classes((SessionAuthentication, TokenAuthentication, BasicAuthentication)) permission_classes((IsAuthenticated,)) def create(self, request): """ Use ObtainAuthToken APIView to validate and create a token. """ return ObtainAuthToken().post(request) this is the view.py file. urls.py router.register('login', views.LoginViewSet, base_name="login") urlpatterns = [ path('', include(router.urls)), path('login/', ObtainAuthToken.as_view()), path(r'api-token-auth/', obtain_jwt_token), path(r'api-token-refresh/', refresh_jwt_token), ] Error Message error -
Receive an object in a view associated with multiple foreign keys. Django, Python
I am trying to get values from a class in my models.py file that is bound by multiple intermediate foreign keys. It looks as shown below. class Masseurs(models.Model): user = models.CharField(max_length=10) #element do zamiany na unikalna nazwe uzytkownika name = models.CharField(max_length=70) description = models.CharField(max_length=400) supply = MultiSelectField(choices=CUSTOMER_ACCESS) payment_method = MultiSelectField(choices=PAYMENT_METHODS) deliver = models.IntegerField() sex = models.CharField(max_length=1, choices=SEX_MASSEURS) def average_rating(self): all_ratings = [list(map(lambda x: x.rating, self.review_set.all()))] return np.mean(all_ratings) def __str__(self): return self.user # these are the days of the week of the year class WorkTime(models.Model): week_of_year = models.CharField(max_length=20) masseurs = models.ForeignKey(Masseurs, on_delete=models.CASCADE) def __str__(self): return self.week_of_year # these are single days class DayTime(models.Model): day_of_week = models.ForeignKey(WorkTime, on_delete=models.CASCADE) day_name = models.CharField(max_length=30) full_time = models.BooleanField(default=None) def __str__(self): return self.day_name # these are individual time units such as ('from 8.00-9.00') class Time(models.Model): day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE) compartment = models.CharField(max_length=11) def __str__(self): return self.compartment Now in my view using get_object_or_404 I take a single object from the table 'Masseurs' as in the view below. views.py def masseur_detail(request, masseurs_id): masseur = get_object_or_404(Masseurs, pk=masseurs_id) daytime = Time.objects.select_related('day_time__day_of_week__masseurs').get(id=masseurs_id) context = {'masseur': masseur, 'daytime': daytime} return render(request, 'masseur/masseur_detail.html', context) Then, using 'daytime', try to get all the hours of work for a particular masseur. However, he receives the error … -
django-otp does not generate new token after a verification of token
Im Using "django-otp" in "Django DRF" for OPT token generation and verification. Am Using TOTP token generation and verification and my token validity is 50 second. It generates same OTP token even after the verification also. i used code as reference: https://medium.com/viithiisys/creating-and-verifying-one-time-passwords-with-django-otp-861f472f602f I want to create new token after a verification MY Code: class TOTPVerification: def __init__(self): # secret key that will be used to generate a token, # User can provide a custom value to the key. self.key = random_hex(20) # counter with which last token was verified. # Next token must be generated at a higher counter value. self.last_verified_counter = -1 # this value will return True, if a token has been successfully # verified. self.verified = False # number of digits in a token. Default is 6 self.number_of_digits = 6 # validity period of a token. Default is 30 second. self.token_validity_period = 35 def totp_obj(self): # create a TOTP object totp = TOTP(key=self.key, step=self.token_validity_period, digits=self.number_of_digits) # the current time will be used to generate a counter totp.time = time.time() return totp def generate_token(self): # get the TOTP object and use that to create token totp = self.totp_obj() # token can be obtained with `totp.token()` token = str(totp.token()).zfill(6) … -
How to upload costumer location to db?
I'm trying to to upload costumer GPS location to db,I got the error massage when running server from django.db import models from django.contrib.gis.db import models as geo_models class Order(models.Model): table_num = models.ForeignKey(Table,on_delete=models.DO_NOTHING) date = models.DateField(auto_now_add=True) value=models.IntegerField(blank=True, null=True,default=0) state=models.IntegerField(default=0) lan= models.IntegerField(default=0) location = geo_models.PointField() def __str__(self): return str(self.id) The error message: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", " gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. -
django query with QuerySet objects
assuming this is my models class Organizer(models.Model): # properties class Event(models.Model): organizer = models.ForeignKey(Organizer,on_delete=models.CASCADE) # other properties class Ticket(models.Model): event = models.ForeignKey(Event,on_delete=models.CASCADE) # other properties class Register(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.SET_NULL, null=True) I have a Organizer object org_obj and I want to get a list of all events that have more than 20 registers made for this Organizer this is my code: events = Event.objects.filter(organizer=org_obj) event20 = [] for e in events.iterator(): tickets = Ticket.objects.filter(event=e) tickets_sold = 0 for t in tickets.iterator(): tickets_sold += Register.objects.filter(ticket=t).count() if tickets_sold > 20: event20.append(e) is there to improve this query not using loops? In plain SQL this should be possible with join expressions and Subqueries. -
Pycharm (JetBrains) cannot modify the read-only directory on my macbook
I am using Mac OS High Sierra and trying to learn Django framework over Pycharm IDE. But my directories are only read only and so I cannot add more files or make changes on the existing files. I tried in Pycharm > File > Make Directory Writeable but it did not help either. This question has been answered for Windows or Ubuntu but those commands do not work at least on my Mac. Anyone knows how to solve this issue? Thanks in advance! -
How to show specefic admin posts in admin panel?
I want to get the current logged in admin to show its posts in admin panel i don't know what's the definition for it in admin.py ? How is it? class ChangeList(admin.ModelAdmin): def get_queryset(self, request, *args, **kwargs): qs = super(ChangeList, self).get_queryset(self, request) if request.user.is_superuser: return qs return qs.objects.get(post_author=request.user, post_privacy='public') -
POST http://127.0.0.1:8000/api/register/ 401 (Unauthorized)
view.py class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ serializer_class = UserSerializer queryset = UserRegister.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateRegister,) This is the view.py file. Here i have added authentication and permission to my view set. model.py class UserRegisterManager(BaseUserManager): """ Helps django work with our custom user model """ def createUser(self, email, name, password=None): """ Creates a new user profile object """ if not email: raise ValueError("User must have an email address.") email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) # set_password helps to convert str into hash user.save(using=self._db) return user def create_superuser(self, email, name, password): """ Creates and saves a new superuser with given details. """ user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserRegister(AbstractBaseUser, PermissionsMixin): """ Represents a 'user register' inside our system """ email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) # user is currently active or not is_staff = models.BooleanField(default=False) objects = UserRegisterManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): """ Used to get user fullname """ return self.name def get_short_name(self): """ Used to get user short name """ return self.name def __str__(self): """ Django uses this when it … -
Django Pivot Table Creation
Good Afternoon, I am working on a Django App. I have created a model like below. From that model I would like to create a view displaying such a table as below: As you can see I would like to create rows per country name in the model database and I would like to give counts per specification. I could create the table with the country names by adding a meta class to the model for the country field and then loop it with template injection. To do that I also created a view as below: def sum(request): country_list_unique = Project.objects.order_by().values('country_ordering').distinct() return render(request, 'project/project_sum.html', {'sumup':country_list_unique}) However, I don't have much of an idea how can I count the different specifications per country in views.py and how to inject them into html with Django. I would appreciate any help. Thank you very much in advance. -
How to change UI language of ckEditor?
I am using ckEditor as my web-based post editor. I know that ckeditor is a multi-lingual application. The problem is that I don't know how could I change the UI from English version, to Arabic one, in Django-ckeditor? -
Django - Is request.user cleared when leaving site?
I'm having this issue, I can't quite figure out. My application flow is as follows: User Authenticates with Twitch User is asked to create a profile at /signup (GET) User Posts to /signup with profile form data and user is created User is automatically logged in User is redirected to /signup and button appears to Auth with Spotify User clicks button is redirected to Spotify auth Spotify redirects to /connect/spotify Now while on /signup, request.user will be my username, CodeSpent, every time. I've tested numerous cases and it will always be accurate on /signup, yet when we get to /spotify/connect, request.user is now AnonymousUser. So my question is if you leave the site, as we do in step 6, is request.user cleared? -
Django Delete OneToOneField
I'm creating a Django web-app. I have an app named vote. I want to "register" this app via a OneToOne-Relationship to other apps. For example I have an article app and I want to "register" vote: vote = models.OneToOneField(Vote, on_delete=models.CASCADE, default=None, null=True) I changed the save method on article: def save(self, *args, **kwargs): self.vote = Vote.objects.create() super().save(*args, **kwargs) Here's the problem: I want vote to be deleten when I delete article but that doesnt work. When I delete article only article will be deleten and vote still exists. -
Nginx won't serve static files
I followed this tutorial to deploy my Django project on DigitalOcean. I've installed Nginx and Supervisor and all worked until I set DEBUG option in the settings.py to False I tried to configure nginx.conf and settings.py million times. Changing root to alias wouldn't help. Nginx configuration file: upstream app_server { server unix:/home/db1/run/gunicorn.sock fail_timeout=0; } server { listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name ...; keepalive_timeout 5; client_max_body_size 4G; access_log /home/db1/logs/nginx-access.log; error_log /home/db1/logs/nginx-error.log; location /static/ { root /home/db1/site1/static; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') -
Collect Data from All apps, and run code after all apps are loaded (Django)
I want to be able to able to inject some configurations from each app, and then run some code after all apps are loaded to load a service with all the provided configurations from all apps. How do I go about implementing that ? -
Matching query doesn't exist Error while searching
I am trying to make a search field and whenever I search for anything this error arise User_Model matching query does not exist. *User_Model is a table views.py def searchForMembers(request): ser = request.GET['member'] allMembers = User.objects.filter(username=ser) return render(request, 'memberMembersPage.html', {'memberList': allMembers}) html page <form class="navbar-form navbar-left" method="get" action="{%url 'searchForMembers'%}"> {%csrf_token%} <div class="form-group"> <input type="text" class="form-control" placeholder="Search for a member" name="member"> </div> </form> -
Calling JQuery function by AJAX
Sequel to my question i tried resolving my problem by calling modalForm from Ajax but again i am confronted with an error. Error My code is as under {% extends 'base.html' %} {% load static %} {% include "devices/_modal.html" %} {% block content %} <div class="container mt-3"> <div class="row"> <div class="col-12 mb-3"> <button class="create-book btn btn-primary" type="button" name="button" onclick="myfunction2('1')" > <span class="fa fa-plus mr-2"></span>Create book</button> </div> </div> </div> {% endblock %} {% block extra_js %} <script type="text/javascript" charset="utf8" src="{% static "user/js/jQuery-3.3.1.js"%}"></script> <script type="text/javascript" src="{% static "user/js/bootstrap.min.js" %}"></script> <script type="text/javascript" charset="utf8" src="{% static "user/js/jquery.bootstrap.modal.forms.min.js"%}"></script> <script type="text/javascript"> function myfunction2($this) { var link ="../addLocation/"; $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } } ); $.ajax({ url: link , contentType: "application/json; charset=utf-8", processData: true, type: 'POST', dataType: 'html', success: function () { window.location = modalForm(link); }, error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); } }); } </script> {% endblock extra_js %} I have even tried no-conflict of Jquery. But i just can't populate the popup modal. I hope there is a work around for it.