Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
1048, "Column 'user_id' cannot be null"
models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=30,blank=False,null=False) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10,blank=True) def __str__(self): return self.fullname forms.py class UserForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'})) password= forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'})) email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'})) password2 = None class Meta: model=User fields=['username','password','email'] class ProfileForm(forms.ModelForm): fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'})) class Meta: model=Profile fields=['fullname'] views.py def register(request): if request.method =='POST': form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): variable=form.save(commit=False) variable.password = pbkdf2_sha256.encrypt(request.POST['password'],rounds=12000,salt_size=32) variable.save() profile=profile_form.save(commit=False) profile.username=variable.username profile.save() username = form.cleaned_data.get('username') messages.success(request,f'account created for { username }') return redirect('login') else: form = UserForm() profile_form = ProfileForm() context={'form':form , 'profile_form':profile_form} return render(request, 'users/register.html',context) I have created two table auth_user (default) and users_profile.When i register the User default data goes into auth table but fullname is not inserted into user_profile. -
Django application structure,
I'm trying to deploy my Django project to Google AppEngine, however I can't figure out how to properly set up application entrypoint. This is my whole project structure: service-master: app.yaml main.py service: manage.py service-project: wsgi.py settings.py ... service-app-1: ... service-app-2: ... How can I make it work? I tried to move main.py to service and use entrypoint: gunicorn --chdir /service main:application in app.yaml but it results in Error: can't chdir to '/service', I guess AppEngine doesn't allow to change directory. -
Displaying title in the django administration instead of object
I have got a main table called Item and table Bike that is connected to Item with OneToOneField. When I add a new Bike using django administration page, it shows as Bike object (1). Is there a way to show the title of that Bike, that is stored in the Item table instead of that "Bike object (1)"? my models.py: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') -
Windows IOError: [Errno 13] Permission denied:
I'm setting up tinymce with Django for the first time and we want to enable image upload. I configured the image upload URL, even managed to pass the CSRF token, otherwise Django wouldn't accept the POST request. Here's the view tinymce is interacting with: @login_required @require_http_methods(['GET', 'POST']) def upload_image(request): if request.method == 'GET': return JsonResponse({'location': settings.IMAGES_DIR}) if request.method == 'POST': with open(settings.IMAGES_DIR, 'wb+') as destination: for chunk in request.FILES['image'].chunks(): destination.write(chunk) I set up settings.IMAGES_DIR as in the local project directory just to test it out. However when the function gets to the part where it starts writing the file I'm getting the following error: IOError: [Errno 13] Permission denied: 'C:\\Users\\xxxxxx\\PycharmProjects\\xxxxx\\media' I am not too familiar with Windows permissions but I checked the folder properties and every user group seems to have write permissions. Now, I'm not sure "who" is the user doing the actual writing, it must be the user running the PyCharm server locally, right? Well, that's just my regular Windows user which is an admin and all, and in any case has write permissions in that folder as I mentioned. What's going on here? PS: yes, I am on Windows and I am using Django 1.8. Please don't … -
What can I do to make 'id' = id in this class-based view in Django?
views.py from django.shortcuts import render from django.views.generic import DetailView from .models import Producto def general_view(request): context = { 'articulos': Producto.objects.all(), } return render(request, 'shop/general_view.html', context) class DetailedView(DetailView): model = Producto template_name = 'shop/specific_view.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['determinado'] = Producto.objects.get(pk=*¿?*) return context urls.py from django.urls import path from . import views from .views import DetailedView urlpatterns = [ path('', views.general_view, name='general-view'), path('<int:pk>/', DetailedView.as_view(), name='specific-article'), ] As you see, the problem occurs because I don't know how to call the id or pk in the detailed_view in views.py, I'm guessing you maybe have to do a dictionary but I don't know where to do it nor how. It works if I set the id to 1, but obviously what this does is that is shows in every url with a different id the same article. -
Deploy django app as static pages on common static web-hosting provider? [closed]
I've worked a few times on django but I'm not an expert and I don't know all the low level functionalities of the framework. With that in mind, I was wondering if there's is a way to deploy a django app as a static website or if there's something out there that generates html pages out of a django project (connecting routes to files, fixing links, etc.) and then store those generated files on static web-hosting provider (i.e. github-pages) I've looked around but I couldn't find anything worth trying out. What do you guys suggest? -
how manage connections of mysql for concurrent request passes from celery
We are using 'django-db-connection-pool' package to manage connection pooling. We are trying to execute two tasks concurrently using celery with two different queues of rabbitmq(rabbitmq is celery broker), one task execute successfully but second task is not succeeded , this will drop mysql connections. if we try both functions without queuing, it will work properly. That means, if concurrent request is passed to mysql that loss mysql connections. for sequential execution it will works properly. Please provide solution to overcome this issue. Thanks in advance. -
Object not being saved to database Django
I have a webapp with a friends feature, which is all working except for the bit of saving the current user into the requested user's ManyToManyField. Here is my model friends = models.ManyToManyField(User,blank=True,related_name='user_connections') And my view class AddFriendRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): username = self.kwargs.get("username") obj = get_object_or_404(UserProfileInfo,slug=username) # print(f'OBJECT: {other}') # print(f'Current user: {self.request.user}') # user_profile = User.objects.get(username=username) url_ = obj.get_absolute_url() user = self.request.user user_ = self.request.user.username # user__ = print(f"HEY YOU! YE! \n{username}\n{obj}\n{url_}\n{user}") if user.is_authenticated: print("User is authenticated") if user in obj.friends.all(): obj.friends.remove(user) user.user_connections.remove(obj) user.save() else: obj.friends.add(user) user.user_connections.add(obj) user.save() return url_ And finally my urls path('profile/<str:username>/add/',views.AddFriendRedirect.as_view(),name='add_friend'), Everything is working except for saving for the user.user_connections.add(obj). On obj.friends.add(user), it adds the current user to their Manytomanyfield, but it's just not working on the user.user_connections.add(obj) one. I have tried heaps of things, including user.friends.add(obj) user.userprofileinfo.friends.add(obj) user.userprofileinfo.user_connections.add(obj) UserProfileInfo is my custom UserProfile model I am just confused as to why this isn't working, and it's weirder because no errors are being thrown either. Thanks for any help -
Working with Django Foreign Keys, Linking to HTML page
I made a Django app for an online school, so I added a foreign key to link the databases Classes and Subjects, I just created A subject in the admin page, linked it into the wanted class, when trying to access it in HTML page I am just having the same subject on all classes, So i thing I used the foreign key the wrong way! how to do it? please help. MODELS.py: class Class(models.Model): image= models.ImageField(upload_to="images") name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) def __str__(self): return self.title class Material(models.Model): name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) classes= models.ForeignKey(Class, default=1, on_delete=models.SET_DEFAULT) def __str__(self): return self.name HTML page: <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <title>Name</title> <link rel="stylesheet" href="static/css/style.css"> </head> <body> <div> <nav> <div class="logo"><img src="static/images/Logo.png" width=50px></div> <ul class="navul"> <li class="navli"><a class="nava" href="404.html">حول الموقع</a></li> <li class="navli"><a class="nava" href="404.html">المكتبة</a></li> <li class="navli"><a class="nava" href="404.html">الدورات</a></li> <li class="navli"><a class="nava" href="/classes">الصفوف</a></li> <li class="navli"><a class="nava" href="/">الصفحة الرئيسية</a></li> <button class="bt1"><a href="#">سجل دخول</a></button> </ul> </nav> <div class="div1"> <img src="static/images/Logo.png" width="90" class="logo2"> <h1 class="t1">الصفوف</h1> </div> <div class="cardrow"> {% for class in class.all %} <div class="cardcolumn"> <a href="{{% url 'material' class.id %}}"> <div class="card"> <img class="imgcls" src="{{ class.image.url }}"> <h1>{{ class.title }}</h1> </div> </a> </div> {% endfor %} </div> </div> </body> </html> … -
How can i delete a database row from a Django view? [duplicate]
I created a form where an user can delete some preferences from the Database. Here is my view: if 'button2' in request.POST: instance = Keys.objects.get(id=request.POST['id']) form2 = DeleteKey(request.POST, instance=instance) if form2.is_valid(): profile = form.save(commit=False) profile.key = '' profile.save() messages.success(request, f"Success") return HttpResponseRedirect(request.path_info) And the form: class DeleteKey(forms.ModelForm): class Meta: model = Keys fields = () def save(self, commit=True): send = super(DeleteKey, self).save(commit=False) if commit: send.save() return send This code works, the problem is that i'm not really deleting the row from my own database, i'm just setting that field to an empty string. Is there any way to completely delete the row, instead? Thanks in advance! -
How to properly write a custom user model and manager in Django v3?
I have a user model like below class User(AbstractBaseUser, PermissionsMixin): class Type: FP = 'fp' BRANCH = 'branch' CHOICES = ( (FP, '채용공고 보기'), (BRANCH, '채용공고 내기'), ) class Sex: MALE = 'male' FEMALE = 'female' CHOICES = ( (MALE, '남성'), (FEMALE, '여성') ) type = models.CharField( max_length=10, verbose_name='계정 종류', choices=Type.CHOICES, ) email = models.EmailField( verbose_name='이메일', unique=True, ) name = models.CharField( max_length=10, verbose_name='이름' ) nickname = models.CharField( max_length=10, verbose_name='닉네임', unique=True, ) phone = models.CharField( max_length=20, verbose_name='전화번호', ) sex = models.CharField( max_length=10, verbose_name='성별', choices=Sex.CHOICES, ) company_name = models.CharField( verbose_name='회사이름', max_length=256, ) dob = models.DateTimeField( verbose_name='생년월일' ) profile_img = models.ImageField( verbose_name='프로필 이미지', upload_to=user_profile_img_file_path, ) sns_id = models.TextField( verbose_name='SNS ID' ) sns_type = models.CharField( verbose_name='SNS 종류', max_length=20, ) objects = UserManager() USERNAME_FIELD = 'email' and custom manager like below class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): sys.stderr.write(repr(extra_fields)) if not email: raise ValueError('이메일은 필수사항입니다') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_superuser = True user.save(using=self._db) return user and test looking like below def test_create_valid_user_success(self): """ Test that creating user with valid payload is successful """ profile_img = self.generate_photo_file() payload = { 'email': 'test@gmail.com', 'password': '1234567', 'type': 'fp', 'name': 'testname', 'nickname': 'testnickname', 'phone': '01012341234', 'sex': 'male', … -
Error after deploying a Django app on Heroku
I am deploying a Django app on heroku , which is successfully deploying, but I am getting the following error when I want to view the app on the provided http link. i am deploying on linux mint mint 19.3.Keep in mind gunicorn is in requirements.txt file. Blockquote 2020-02-21T16:22:09.021935+00:00 heroku[web.1]: State changed from crashed to starting 2020-02-21T16:22:18.635625+00:00 heroku[web.1]: Starting process with command `gunicorn brendan_project.wsgi -- log file-` 2020-02-21T16:22:20.734759+00:00 heroku[web.1]: Process exited with status 127 2020-02-21T16:22:20.679520+00:00 app[web.1]: bash: gunicorn: command not found Blockquote Hear is my requirements.txt file Blockquote asgiref==3.2.3 astroid==2.3.3 certifi==2019.11.28 chardet==3.0.4 dj-database-url==0.5.0 Django==3.0.2 django-crispy-forms==1.8.1 django-fontawesome==1.0 django-heroku==0.3.1 django-mailjet==0.3.1 django-sendgrid==1.0.1 django-smtp-ssl==1.0 gunicorn==20.0.4 idna==2.8 isort==4.3.21 lazy-object-proxy==1.4.3 mailjet-rest==1.3.3 mccabe==0.6.1 psycopg2==2.8.4 pylint==2.4.4 pytz==2019.3 PyYAML==5.3 requests==2.22.0 six==1.14.0 sqlparse==0.3.0 typed-ast==1.4.1 urllib3==1.25.7 whitenoise==5.0.1 Blockquote -
Why am I getting syntax error in nested if..else statement in Django views
I believe in Python we can do the following: if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) elif expression4: statement(s) else: statement(s) else: statement(s) I am trying to do something like this in Django views: if qs1.count() > 100: # do something elif qs1.count() - qs2(count) < 12: # do something else elif qs3.count() > qs2.count(): if qs1.count() == qs3.count(): # Error here << # do whatever else: # forget it I am getting SyntaxError: invalid syntax at the code line shown. What am I doing wrong? How do I improve the statement flow so as not to encounter an error. -
Django redirection to another page not working
So I'm trying to create a webstore using Django and HTML. To make it short, my problem is that when I press the button "Products" on the navigation bar it gives me an 404 error. This is the error it gives me. It also gives me errors in the terminal The error in the terminal. I have been trying to figure out what's wrong for the past hour but nothing seems to be working. Here's my code; (The file product.html is located in a folder named "templates") My views.py file from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Item # Skriptist models.py impordib eseme (Item'i) # def product(request): context = { "items": Item.objects.all() } return render(request, "product.html", context) def checkout(request): return render(request, "checkout.html") class HomeView(ListView): model = Item template_name = "home.html" class ItemDetailView(DetailView): model = Item template_name = "product.html" My urls.py file from django.urls import path from django.conf.urls import include, url from .views import ( ItemDetailView, checkout, HomeView ) # Skriptist views.py improdib "item_list'i" # app_name = "core" urlpatterns = [ path('', HomeView.as_view(), name='home'), path('checkout/', checkout, name='checkout'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), ] And finally this is my scripts.html file which has all of the javascript stuff. {% … -
How do I increase an IntegerField in Django?
I am making a Todo list web app in Django. I am just learning Django and a very much novice, so any help is greatly appreciated. My problem: My app will allow users to sign up and they can have a profile of their own. They can create ToDos and delete them as they want. Now, I want to introduce an attribute to all the users called "todos". This is basically an integer value that will keep track of how many todos they have created since they signed up. And every time the user adds a new task, I want this value to increase by 1. I just can't seem to figure out how to implement this. This is my models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") todos = models.IntegerField(default=0) def __str__(self): return f"{self.user.username} Profile" def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) views.py class TodoListView(ListView): model = ToDo template_name = "ToDo/home.html" context_object_name = "todos" ordering = ["-date_posted"] class TodoCreateView(CreateView): model = ToDo fields = ["title"] success_url = reverse_lazy("todo-home") def form_valid(self, form): … -
Django does not make migrations of multiple models under app_label?
class User(models.Model): ...... ...... class Meta: app_label = 'app_name' class Customer(models.Model): ...... ...... class Meta: app_label = 'app_name' Only User model is created but Customer model is not created. I am creating models out of app scope -
Django pop up modal after Inserting/updating data
I've been searching on google and SO but that doesnt work when i apply it to my code, I just want that if the user update/insert data, a pop up modal message appears I have this form in my html <form method="post" id="myform" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table id="blacklistgrids" border="2px"> <tr> {% for v in table.0 %} {% if forloop.first %} <th id="thupdate">{{v}}</th> {% else %} <th ><input type="text" name="updatedate" value="{{ v }}"></th> {% endif %} {% endfor %} <th hidden></th> <th data-id='headerss' id='headerave'>Average</th> </tr> <tbody> {% for row in table|slice:"1:" %} <tr class="tr2update"> <td><input type="text" value="{{row.0}}" name="students" hidden>{% for n in teacherStudents %}{{n.Students_Enrollment_Records.Student_Users}}{% endfor %}</td> <td class="tdupdate" hidden><input type="text" hidden></td> {% for teacher in students %} <input type="hidden" name="id" value="{{teacher.id}}"/> <td> <input type="text" data-form-field="{{teacher.id}}" name="oldgrad" class="oldgrad" value="{{teacher.Grade|floatformat:'2'}}"/> </td> {% endfor %} {% for avg in average %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" value="{{average.average_grade|floatformat:'2'}}" readonly/></td> {% endfor %} </tr> {% endfor %} </tbody> </table> <div class="buttons"> <input type="submit" value="&nearrow;&nbsp;Update" class="save" formaction="/updategrades/"> <!--formaction="/updategrades/"--> </div> </form> <script> if (typeof jqXhr.success != 'undefined') { $('#thanksModal').modal('show'); } else { $('#myform').html(jqXhr); } </script> and this is my views.py import json def updategrades(request): /some logic/ return HttpResponse(json.dumps({"success":True}), content_type="application/json") -
Django 2.2 - django.db.utils.OperationalError: no such table
I am pulling my hair out. I just can't get migrations to work anymore. Every time I run python3 manage.py makemigrations or python3 manage.py makemigrations app_name I get the following error: Traceback (most recent call last): File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: catalog_fault The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/urls/resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/urls/resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/importlib/__init__.py", line … -
Change integer field value with update_or_create method for an inlineformset
I have 2 models: class Contract(models.Model): number = models.CharField( blank=False, null=False, default="", max_length=255, ) date = models.DateField( blank=False, null=False, ) slug = models.SlugField(blank=False, null=True, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) def save(self, *args, **kwargs): self.slug = slugify(self.number) super(Contract, self).save(*args, **kwargs) class ContractItems(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE, related_name='contractitmes_set') item = models.ForeignKey( Catalog, on_delete=models.CASCADE, blank=False, ) quantity = models.PositiveIntegerField() forms.py class ContractAddForm(forms.ModelForm): class Meta: model = ContractItems exclude = () class ContractForm(forms.ModelForm): date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ), ) class Meta: model = Contract fields = ( 'number', 'date', ) ContractAddFormSet = inlineformset_factory( Contract, ContractItems, form = ContractAddForm, extra = 1, ) In views i pass inlineformset so that, when i create Contract i cant also create as many ContractItems as i want. views.py class ContractCreate(LoginRequiredMixin, CreateView): model = Contract fields = ['number', 'date', 'author'] class ContractAddItemsCreate(LoginRequiredMixin, CreateView): model = Contract # fields = ['number', 'date', 'author'] success_url = reverse_lazy('tabs') form_class = ContractForm def get_context_data(self, *args, **kwargs): data = super(ContractAddItemsCreate, self).get_context_data(**kwargs) if self.request.POST: data['contractitems'] = ContractAddFormSet(self.request.POST) else: data['contractitems'] = ContractAddFormSet() return data def form_valid(self, form): context = self.get_context_data() contractitems = context['contractitems'] with transaction.atomic(): form.instance.author = self.request.user self.object = form.save() if contractitems.is_valid(): contractitems.instance = self.object contractitems.save() return super(ContractAddItemsCreate, self).form_valid(form) What i … -
Django ORM Group by, Sum with row ID to get position of user on leaderboard
I want to create a leaderboard from the below table. I have managed to do a sum group by of the table based on points, but now I want to extract the row index of specific user to display only his position on the leaderboard Table =# Select * from user_activity; user_activity_id | user_activity_date | user_activity_point | user_activity_description | user_activity_document_id | user_activity_user_id ------------------+-------------------------------+---------------------+---------------------------+--------------------------------------+----------------------- 24 | 2020-02-28 08:32:22.17622+00 | 2 | Page Classification | e516c38c-5f96-4e46-af15-aa6dcbe30184 | 2 ORM leaderboard = User_Activity.objects.values('user_activity_user_id').order_by('points').annotate(points=Sum('user_activity_point')) So now this brings back a queryset which I can loop over to get the index of the specific user and use that as his position, but surely there must be a better way to get the index directly from the query -
Not displaying details in database
I am not able to get the deatils of the beneficiary in the database when I fill up the form for beneficiary and husband the details of only the husband is shown in the database and the details of the beneficiary is somewhat lost.The fields of the beneficiary are all empty. <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/" enctype="multipart/form-data" id="regForm"> <div class="group"> <div class="tab"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <!--Beneficiary Details--> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="formGropuNameInput">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="adhaarno" class="form-control" id="aadhar" pattern="[0-9]{4}[0-9]{4}[0-9]{4}" placeholder="Enter Aadhar Card number with proper spacing" required> </div> <input type="file" name="adhaarcopy" /> <div class="form-group"> <div class="form-check"> <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required> <label class="form-check-label" for="invalidCheck3"> Give consent to collect adhaar card data </label> <div class="invalid-feedback"> You … -
Pythonanywhere: Error running WGSI application
I'm trying to run a Django app in pythonanywhere, and I'm running into a WGSI application problem. I'll try to explain the things I've tried: When I run the server from the console on pythonanywhere with "manage.py runserver" it doesn't have any problems. The error looks like this: 11:13:54,818: Error running WSGI application 11:13:54,818: ModuleNotFoundError: No module named 'atrapamente.settings' 11:13:54,819: File "/var/www/atrapamente_eu_pythonanywhere_com_wsgi.py", line 11, in <module> 11:13:54,819: application = get_wsgi_application() 11:13:54,819: 11:13:54,819: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 11:13:54,819: django.setup(set_prefix=False) 11:13:54,819: 11:13:54,820: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup 11:13:54,820: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 11:13:54,820: 11:13:54,820: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ 11:13:54,820: self._setup(name) 11:13:54,820: 11:13:54,820: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup 11:13:54,820: self._wrapped = Settings(settings_module) 11:13:54,821: 11:13:54,821: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ 11:13:54,821: mod = importlib.import_module(self.SETTINGS_MODULE) 11:13:54,821: *************************************************** 11:13:54,821: If you're seeing an import error and don't know why, 11:13:54,821: we have a dedicated help page to help you debug: 11:13:54,821: https://help.pythonanywhere.com/pages/DebuggingImportError/ 11:13:54,822: *************************************************** On the console, I tried finding the WGSI file as they explain on the help page. Then I checked if I could import my settings and the path. Apparently there are no problems there. I checked it like this: (venv) Atrapamente@green-euconsole1:~/atrapamente$ python3.7 -i /var/www/atrapamente_eu_pythonanywhere_com_wsgi.py >>> import atrapamente.settings … -
502 Bad Gateway nginx with Selenium and Django
I have a web-app with DigitalOcean (gunicorn/nginx) using Selenium and Django. I'm trying to scrap data from 3 websites and save this data in a database, but I get this error if the process take more than 60 seconds 502 Bad Gateway nginx/1.14.0 (Ubuntu) How can I extend or disable response waiting time for nginx ? -
Crontab with django: ValueError not enough values to unpack
I'm implementing crontab with my django project and am getting a error which I'm unable to figure out the cause of: Traceback (most recent call last): File "/Users/stein/Documents/renbloc/api_web/ebdjango/manage.py", line 19, in execute_from_command_line(sys.argv) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django_crontab/management/commands/crontab.py", line 29, in handle Crontab().run_job(options['jobhash']) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django_crontab/crontab.py", line 141, in run_job module_path, function_name = job_name.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) I have the following in the settings.py file: Cron_Dir = BASE_DIR + '/api/cron/my_cron_job' CRONJOBS = [ ('* * * * *', Cron_Dir) ] and the function my_cron_job is just: def my_cron_job(): a = 1+1 I first thought crontab somehow got 2 functions registered instead of one but after removing all tasks with: python manage.py crontab remove and then adding the tasks again I still get the same error. Would really appreciate some help. -
django rest framework filter on related tables
i need help filtering on a field on a related table. I have tow models Kalas and names, where one (Kalas model) has a one to one relation with the basic User model: class Kalas(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) visitKalas = models.ForeignKey('self', on_delete=models.DO_NOTHING, blank=True, null=True) isActive = models.BooleanField(default=True) capacity = models.IntegerField(default=0) fullName = models.CharField(max_length=100, default="default name") phoneNumber = models.IntegerField() address = models.CharField(max_length=40) postal = models.CharField(max_length=50) time = models.DateTimeField(auto_now_add=True) lat = models.FloatField(default=0) lng = models.FloatField(default=0) def __str__(self): return "user: %s, address: %s %s" % (self.user, self.address, self.postal) class names(models.Model): kalasID = models.ForeignKey(Kalas, on_delete=models.CASCADE, related_name='names') name = models.CharField(max_length=30) and i have made a nested serializer: class NamesMapSerializer(serializers.ModelSerializer): class Meta: model = names fields = ['name'] class KalasMapSerializer(serializers.ModelSerializer): #bruk denne hver gang man vil ha kalas og navn sammen names = NamesMapSerializer(many=True, read_only=True) class Meta: model = Kalas fields = ['id', 'fullName', 'capacity', 'lat', 'lng', 'names'] class MapSerializer(serializers.ModelSerializer): kalas = KalasMapSerializer() class Meta: model = User fields = ['username', 'kalas'] and a view that lists all users and its kalas with names: class MapViewSet(viewsets.ModelViewSet): queryset = User.objects.all() permissions_classes = [permissions.AllowAny] serializer_class = MapSerializer but i dont know how to filter so it only shows users with kalas that i active kalas.isActive=True. i've tried …