Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save Data to Django Model
I need to save Subscribe from Data to Django models. I am using react.js and Django. I have tried to make an API to POST request in Django. And then I have tried to connect this API with react subscribe form. I am doing this in order to store this in the database. Here is what I have code so far. But the code is wrong it's not working can someone guide me.I believe I am missing the react part. Subscribe.js import React from "react"; import "./Subscribe.css"; const Subscribe = () => { return ( <div class="loginModule" style={container}> <div class="extraBorder"> <form class="loginForm"> <div class="welcome">Get weather updates</div> <input type="text" name="name" class="sub_name" placeholder="Name" /> <br /> <input type="email" name="email" class="sub_email" placeholder="Email" /> <br /> <input type="submit" class="sub_btn" value="Subscribe" /> </form> </div> </div> ); }; export default Subscribe; views.py from django.shortcuts import render import os import requests from requests.auth import HTTPBasicAuth def api(request): name = request.POST.get('name') email = request.POST.get('email') url = os.environ.get("URL", 'http://myhost:port/projectname/api/addposition?compName=Google&category=Developer') url = "%s" % (url) body = {"name" : "%s" % name, "email" : "%s" % email} response = requests.post(url, auth=HTTPBasicAuth('USER', 'PASSWORD'), headers={'Content-Type': 'application/json'}, json=body) if response.status_code == 200: print("Code 200") else: print("Code not 200") url.py from django.contrib import admin … -
Updating all values in table in Django
I have a Django model class Hnap(models.Model): name=models.TextField(default='USD') value=models.DecimalField(max_digits=10, decimal_places=5, default=0) The content of the table is of the form ID name value 1 USD 23.44 2 GBP 53.12 My View is def hnap(request): try: currency = Hnap.objects.all() if request.method == "POST": post_values = request.POST.copy() except Exception as ex: print(ex) context = { 'currency': currency, 'errors': errors, } return render(request, 'hnap.html', context) My template displays the name and puts the values in a textbox and assigns the name curr_(value of the index) <form action="{% url 'hnap' %}" method="POST"> {% for i in currency %} <div class="row"> <div class="col">{{i.name}}</div> <div class="col "><input type="text" class="form-control" name="curr_{{i.id}}" required value="{{i.value}}"></div> </div> {% endfor %} </form> How do I write the view so that all the values in the text input are updated at one go? -
Passing context object name to html directly like href="{% url 'profileEdit' here %}" in django
Here I am trying to edit the profile of the user which is currently logged in. urls.py path('profileEdit/<int:pk>/',views.profileEdit.as_view(),name='profileEdit'), views.py class profileEdit(UpdateView): model = Profile fields = ['bio', 'photo'] template_name = 'Blog/profileEdit.html' success_url = '/newsfeed/' context_object_name = 'form' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def profileuser(): me = Profile.objects.get(user=request.user) contex={ 'u':me.pk, } return render(request,'Blog/base.html',contex) base.html <div class="dropdown-menu"> <a class="dropdown-item" style="font-size:20px;color:red" href="{% url 'profileEdit' something %}">Edit Profile </a> I want to put something in something through which can get URL like 'profileEdit/2/'. In place of something we can put like request.user.pk but the problem is that I don't want to get user pk. Instead of that, I want profile pk so, I created profileuser function through which I can pass context object to html url but don't know how to do. -
Kombu Celery on message failure
I am currently using kombu to send a message between two application, and it is running seamlessly. The only problem is when I receive a message at clientB from clientA and I reject it (instead of ack). I do not get a notification at clientA. I need an onfailure method or similar behaviour. -
How best to use ansible pexpect with django createsuperuser?
Task is to create django superuser with Ansible, added with password value from a variable. I tried Ansible's django_manage like this - name: Super User django_manage: command: "createsuperuser --username={{backend_admin}} --email=admin@{{ domain }}" app_path: "/home/{{parent}}/{{component}}/" virtualenv: "/home/{{parent}}/venv" environment: DJANGO_SUPERUSER_PASSWORD={{admin_pass}} tags: - initial It creates admin user but doesn't set the given password. I even tried adding this suggestion in my command section of this django_manage task like this django_manage: command: shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('{{ backend_admin }}', 'admin@example.com', '{{ admin_pass }}')" but still it creates user with password other than that defined in variable. So I thought Ansible's pexpect module would suffice and I created a task with that. - name: Super User expect: command: "/home/{{project}}/venv/bin/python /home/{{project}}/{{component}}/manage.py createsuperuser --username={{backend_admin}} --email=admin@{{ domain }}" responses: 'Password:': "{{ admin_pass }}" 'Password (again):': "{{ admin_pass }}" I made sure python pexpect & setuptools libraries are installed on target node. But I'm getting this incomprehensible error now by Ansible ERROR: fatal: [staging]: FAILED! => {"changed": true, "cmd": "/home/project/venv/bin/python /home/project/backend/manage.py createsuperuser --username=debdeb --email=admin@project.local", "delta": "0:00:01.282593", "end": "2020-10-20 13:23:39.083390", "msg": "non-zero return code", "rc": 1, "start": "2020-10-20 13:23:37.800797", "stdout": "Traceback (most recent call last):\r\n File \"/home/project/venv/lib/python3.6/site-packages/everett/manager.py\", line 950, in __call__\r\n parsed_val = parser(default)\r\n File \"/home/project/backend/project_server/settings.py\", line … -
psycopg2.errors.NotNullViolation: null value in column "id_id" violates not-null constraint
Below is my model Windows 10, postgress 12, django 3.0.7, python 3.7.6 class User(AbstractBaseUser, PermissionsMixin): email = models.CharField(max_length=30) password = models.CharField(max_length=4000) first_name = models.CharField(default='', max_length=15) last_name = models.CharField(default='', max_length=15) login = models.CharField(max_length=15) age = models.IntegerField() street = models.CharField(blank=True, max_length=255) city = models.CharField(blank=True, max_length=255) zip = models.CharField(blank=True, max_length=10) role = models.CharField(default='', max_length=10) USERNAME_FIELD = 'id' When I make a post request I'm getting below error File "C:\Users\Akila\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "id_id" violates not-null constraint DETAIL: Failing row contains (null, default). -
Invoking flask in Django and get output in Django screen
I want to invoke flask URL in Django and want to get output depending on the value which we are giving in the form of Django screen flask.py from flask import Flask, jsonify import requests app = Flask(__name__) @app.route('/<name>',methods=['GET']) def index(name): return jsonify({ 'out' : "Hello"+ " "+str(name)}) if __name__== "__main__": app.run(debug=True) views.py from django.shortcuts import render from django.http import HttpResponse import requests def form(request): return render(request,'hello/output.html') def output(request): name1=request.GET.get("name") if not name1: name1=0 respons=requests.get('http://127.0.0.1:5000/' + str(name1)).json() return render(request, 'hello/index.html',{'out':respons['out']}) output.html <body> <form action = "output" method="GET"> Enter name: <br/> <input type="text" name="name"> <br/> <input type="submit"> <br/> </form> index.html {{ out }} urls.py from django.contrib import admin from django.urls import path from polls.views import output urlpatterns = [ path('output/',output), path('admin/', admin.site.urls), ] after using these code I am getting page not found error -
Django Form is_valid() not compatible with python3
We are using django 2.2.6 and python3 in our application. While using django forms, I am calling this form.is_valid() method and getting this error 'dict' object has no attribute 'iteritems'. Apparently is_valid() uses dict.iteritems() while iteritems() has been removed in python3. I somehow have to get it to call dict.items(). Any suggestions on how I can do this? Please help. Thank you for your time. -
How to update UserProfile connected through one-to-one field with CustomUser model in django, using django_rest_auth and django rest framework ??
I am using dj_rest_auth which is forked from django_rest_auth with djangorestframework. I want to update the UserProfile from the same API ,where I create user. This is my CustomUser model- class User(AbstractUser): email = models.EmailField(unique=True) full_name = models.CharField(max_length=150, verbose_name='Full name') date_updated = models.DateTimeField(auto_now=True) username = None first_name = None last_name = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email This is my UserProfile model- class UserProfile(models.Model): user = models.OneToOneField(User , related_name='user_profile', on_delete=models.PROTECT) profile_picture = models.CharField(max_length=400, null=True, blank=True) contact = models.CharField(max_length=20, unique=True) dob = models.DateField() age_group = models.ForeignKey(AgeGroup, on_delete=models.PROTECT) profession = models.ForeignKey(Profession, on_delete=models.PROTECT) interested_in = models.ManyToManyField(Interest) is_married = models.BooleanField(default=False) country = models.ForeignKey(Country, on_delete=models.PROTECT) state = models.ForeignKey(State, on_delete=models.PROTECT) city = models.ForeignKey(City, on_delete=models.PROTECT) is_profile_completed = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'user_profile' def __str__(self): return str(self.user.email) def clean(self): # Don't allow people less than 18 age_in_days = (datetime.date.today() - self.dob).days print(age_in_days) age = age_in_days / 365 print(age) if age < 18: raise ValidationError(gettext_lazy('You should be an adult (18+).')) This is my UserSerializer- class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['pk', 'full_name', 'email', 'is_superuser', 'is_staff', 'is_active',] read_only_fields = ('email', 'is_superuser', 'is_staff', 'is_staff') This is my UserProfileSerializer- class UserProfileSerializer(UserSerializer): contact = serializers.CharField(source="user_profile.contact") … -
Chart of price changes in django
I am going to get a chart of product price changes. By creating a new model and using the signal, every time I update the product information, the product model information is stored in my new model. I only want this to happen when I change the price of the product (for example, if I change the number of products or the discount percentage or ... this does not happen). Please help me, thanks my product model: class Product(models.Model): name = models.CharField(max_length=300) create = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) unit_price = models.PositiveIntegerField(default=0) .... my Chart model: class Chart(models.Model): name = models.CharField(max_length=100, blank=True, null=True) create = models.DateTimeField(blank=True, null=True) update = models.DateTimeField(blank=True, null=True) unit_price = models.PositiveIntegerField(default=0, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='pr_update') my signal: def product_post_saved_receiver(sender, instance, created, *args, **kwargs): product = instance Chart.objects.create(product=product, name=product.name, create=product.create, unit_price=product.unit_price, update=product.update) post_save.connect(product_post_saved_receiver, sender=Product) -
Call model method with multiple arguments on django template
My model: class InflacConstraint(models.Model): date_from = models.DateField() date_to = models.DateField() constraint_type = models.CharField(choices = CONSTRAINT_CHOICES, max_length = 32) attribute = models.ForeignKey(ExtraField, null = True, blank = True, on_delete = models.DO_NOTHING) def calc(self, vacations = False, external = False): return self.task.calc(self.date_from, self.date_to, vacations = vacations, external = external) How would one call object.calc(vacations = True, external = True) inside the django template? -
Is there any way to enter a Django template variable via a post form so that a user would not be able to find that in a developer panel?
Currently .html looks like that: [How to make the next fields completely inaccessible?][3] -
I get a 400 Error when I run test with Graphene Django test Utils
I am making use of GraphQL and I am trying to write tests in using the GraphQLTestCase but I get 400 error. Here is my code. import json from graphene_django.utils.testing import GraphQLTestCase from resume.graph.schema import schema from .models import Post from django.contrib.auth import get_user_model from graphql_jwt.shortcuts import get_token from django.contrib.auth import authenticate User = get_user_model() class PostTestCase(GraphQLTestCase): def test_post_list(self): user = User.objects.create(first_name = "john", last_name ="benjamin", email='johnzeus14@gmail.com', password = "oldskool123") # user.set_password("oldskool123") # user.save() token = get_token(user) headers = {"HTTP_AUTHORIZATION": f"JWT {token}"} response = self.query( ''' query { post{ user text } } ''', op_name = 'Post', headers=headers, ) content = json.loads(response.content) self.assertResponseNoErrors(response) when I run this code I get this error below.------------------------------------------ FAIL: test_post_list (post.tests.PostTestCase) Traceback (most recent call last): File "C:\Users\Udemezue\Desktop\resume\post\tests.py", line 61, in test_post_list self.assertResponseNoErrors(response) File "C:\Users\Udemezue\Desktop\resume\env\lib\site-packages\graphene_django\utils\testing.py", line 112, in assertResponseNoErrors self.assertEqual(resp.status_code, 200) AssertionError: 400 != 200 Ran 1 test in 0.030s FAILED (failures=1) Destroying test database for alias 'default'... I have tried all I know but not working. -
how to post using a token in rest-auth with axios? POST http://localhost:8000/rest-auth/password/change/ 401 (Unauthorized)
This is my code in vue, resetPOST(){ var formData = new FormData(); formData.append('old_password', this.oldPassword); formData.append('new_password1', this.password1); formData.append('new_password2', this.password2); axios.post('http://localhost:8000/rest-auth/password/change/', {headers: { 'Authorization' : this.token }, data: { old_password: this.oldPassword, new_password1: this.password1, new_password2: this.password2 } }) }, where the variable 'token' has a value like that : bbf957d27925a860f8c678546cf0425dbf7ddf98 I do not understand why I get this error, if I try the back part I enter the old password, and the two new passwords and it works. For some reason I it isn't taking the token parameter. Thanks in advance -
Validate CSV file according to data in header in Django
In my Django admin i am uploading a CSV file and downloading it. i have two columns Test case ID and Summary. Test Case ID,Summary TC-1,Verify that Process CSV sub module is displayed under “Process CSV” module on Dashboard of Client’s user. TC-2,Verify that Process CSV sub module is displayed under “Process CSV” module on Dashboard of Client’s user. TC-3,Verify the dashboard. TC-4,“verify that user is able to update 'active' attribute 'false ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'true'” TC-5,“verify that user is able to update 'active' attribute 'true ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'false'” I want to add a validation like if the data under Test Case ID is empty the should be error message "All Summaries should have respective Test Case ID' I have added validation for headers .like if header is not present but don't know how to add validation for data under the respective headers. Forms.py class CsvUpload(forms.Form): csv_file = forms.FileField() def clean_csv_file(self): # Probably worth doing this check first anyway value = self.cleaned_data['csv_file'] if not value.name.endswith('.csv'): raise forms.ValidationError('Invalid file type') try: data = pd.read_csv( value.file, encoding='ISO-8859-1', … -
Visual Studio Code in Django
I'm confused why my Vs Code didn't recognize my Django it shows error in my vscode but actually it's not error in coding. I have Django version 2.2.16 and I already installed Django in Vscode and python 3.5 as well. Can anyone know about this? -
How to convert a dictionary list to JSON
I'm trying to peform an A/B test of two ML models and I require to parse data to the model via json. Below is the code for i in range(100): input_data = dict(X_test.iloc[i]) target = y_test.iloc[i] r = requests.post("http://127.0.0.1:8000/api/v1/ddos_classifier/predict?status=ab_testing", input_data) response = r.json() # provide feedback requests.put("http://127.0.0.1:8000/api/v1/mlrequests/{}".format(response["request_id"]), {"feedback": target}) input_data is in the form of a dictionary The code returns this error: JSONDecodeError: Expecting value: line 1 column 1 (char 0) What could be the issue -
Change boolean value and refresh page Wagtail
i added a custom button to my page list in my wagtail admin. Now i want to add a function that sets a boolean in that specific page from false to true and vice versa once the admin clicks the new custom button as well as reload the page. #admin.py class ProductButtonHelper(ButtonHelper): # Define classes for our button, here we can set an icon for example view_button_classnames = ['button-small', 'icon', 'icon-site'] def view_button(self, obj): # Define a label for our button text = 'Objavi na Vojvodjanski' return { 'url': obj,#here i think the url should be the same page that you're on 'label': text, 'classname': self.finalise_classname(self.view_button_classnames), 'title': text, } def get_buttons_for_obj(self, obj, exclude=None, classnames_add=None, classnames_exclude=None): """ This function is used to gather all available buttons. We append our custom button to the btns list. """ btns = super().get_buttons_for_obj(obj, exclude, classnames_add, classnames_exclude) if 'view' not in (exclude or []): btns.append( self.view_button(obj) ) return btns Thanks -
Django superuser not having all permissions
While trying to create a Django Rest Framework endpoint for displaying a users permissions, I encountered a problem when it comes to superusers. I thought superusers had all permissions by default, but when I tried to get all permissions for any user through the Permission-model, I got a length difference between the lists. # User is a superuser > len(user.get_all_permissions()) 516 > len(Permission.objects.all().distinct()) 519 Since get_all_permissions() returns a list instead of a QuerySet, I am unable to see exactly which permissions the superuser lacks. Am I wrong in my impression that a superuser has all permissions? Are there other ways to get all permissions for a user in the form of a Permission QuerySet? I could always just return the list given by user.get_all_permissions() instead of a QuerySet, but this confuses DRF-Swagger when it comes to the format of possible responses. -
Create multiple related objects in form, Django template
I'm new to Django and im trying to create a recipebook. I want to create a recipe and in the same form add a variable number of ingredients. In the form the user should be able to fill in one ingredient and click a button to add another as needed. Here are my models: class Recipe(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=128, blank=False) image = models.ImageField(upload_to='recipe_images/', null=True, blank=True) instructions = models.TextField(blank=False) tips = models.TextField(blank=True) cooking_time = models.IntegerField(blank=False, null=False) course = models.ForeignKey("Course", on_delete=models.CASCADE, null=False) category = models.ForeignKey("Category", on_delete=models.CASCADE, null=True, blank=True) tags = models.ManyToManyField("Tag", related_name='recipes', null=True, blank=True) def __str__(self): return self.title class Unit(models.Model): unit = models.CharField(max_length=128, blank=False) def __str__(self): return self.unit class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name="ingredients") name = models.CharField(max_length=128, blank=False) quantity = models.DecimalField(max_digits=8, decimal_places=2) unit = models.ForeignKey(Unit, on_delete=models.CASCADE) def __str__(self): return self.name class Course(models.Model): course = models.CharField(max_length=128) def __str__(self): return self.course class Category(models.Model): category = models.CharField(max_length=128, blank=False) def __str__(self): return self.category class Tag(models.Model): tag = models.CharField(max_length=64, blank=False) def __str__(self): return self.tag I'm breaking my head over how to do this in the template. I could create a form for the recipe with a modelform and create a seperate list with javascript for the ingredients and send in in json … -
Good practice to implement a ThreadPool of intensive processing inside a Django App
I'm working with Django using Daphne (so, It's an async app). In my site users can run expensive experiments. I'd like the users not to wait, so I decided to implement a "global" ThreadPool running in background. These are the steps I followed: I made a Singleton service: class TaskQueue(object): def __new__(cls): if cls.instance is not None: return cls.instance else: # Creates the instance cls.instance = super(TaskQueue, cls).__new__(cls) cls.instance.executor = ThreadPoolExecutor(max_workers=settings.THREAD_POOL_SIZE) # Gets the pending experiments cls.instance.get_not_computed_experiments() return cls.instance def eval_mrna_gem_experiment(self, experiment: Experiment) -> None: # Some long code... def add_experiment(self, experiment: Experiment): self.executor.submit(self.eval_mrna_gem_experiment, experiment) @lru_cache(maxsize=None) def get_queue(): """ Caches the TaskQueue instantiation """ return TaskQueue() Every time a user makes a request to execute an experiment I do: get_queue().add_experiment(new_experiment) I think this way there's a global queue which computes the experiments in order. The questions are: Is there a correct way to implement that? Keep in mind that in eval_mrna_gem_experiment I make several call to R apis in the SO using rpy2, so I don't know if It's a bad practice as there is a Main Thread (the app) deploying a ThreadPool which calls R code which has several threads running to compute expensive stuff. Does Singleton pattern apply … -
Django 'function' object has no attribute '_meta'
I have a simple Django app where I want to display and save some data from a model. This is my model class Curr(models.Model): name=models.TextField(default='USD') value=models.DecimalField(max_digits=10, decimal_places=5, default=0) My Model Form class CurrForm(forms.ModelForm): class Meta: model = Curr fields = '__all__' My View currency = Curr.objects.all() if request.method == "POST": post_values = request.POST.copy() form = CurrForm(post_values, instance=currency) This gives the error 'function' object has no attribute '_meta' Reading the other similar posts did not clear my doubts. Any help is appreciated. -
Class based view Django
how convert this code to class based code def detail_article(request, slug): context = { "article": get_object_or_404(Articles, slug=slug, state="p") "slider" : Articles.objects.filter(state="p").order_by('-publish')[:20] } return render(request, "blogApp/detail_article.html", context) I tried this : class ArticleDetail(DetailView): context_object_name = 'slider' def get_queryset(self): return Articles.objects.filter(state="p").order_by('-publish')[:6] def get_object(self): slug = self.kwargs.get("slug") return get_object_or_404(Articles, slug=slug, state="p") but I got this error : 'Articles' object is not iterable and also i have for loop in my template on slider -
Django No WSGI daemon process has been configured
I have a Django project loaded up with Lightsail. I'm looking to get it to run with Apache. I've followed the tutorial located here, but for some reason, it is throwing the following site error and apache error when trying to connect to the server by just it's IP. Getting the following error when hitting my site: 500 Internal Server Error When looking at my Apache Logs No WSGI daemon process called 'smp_api' has been configured: /home/ubuntu/test/smp_api/wsgi.py, WSGI.py File import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smp_api.settings") application = get_wsgi_application() Apache Conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/test/static <Directory /home/ubuntu/test/static> Require all granted </Directory> <Directory /home/ubuntu/test/smp_api> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /test> Require all granted </Directory> WSGIDaemonProcess python-path=/home/ubuntu/test WSGIProcessGroup smp_api WSGIScriptAlias / /home/ubuntu/test/smp_api/wsgi.py </VirtualHost> -
unable display variables on webpage in Django
I am unable to show data from the database to HTML. I am getting ordered dict from the serializer. views.py material_class = Material.objects.filter(material_class=user_class.user_class) data = MaterialSerializer(material_class, many=True) content = {'material':data.data} # In *data.data* I am getting this [OrderedDict([('id', '123'),('material','456')]), OrderedDict([('id','345'),('material','789')])] return render(request, 'dashboard/dashboard.html',content) dashboard.html {% load static %} {% csrf_token %} <!DOCTYPE html> <html lang="en"> <head> {% block content %} {% for a in content %} <p>{{ a }}</p> {% endfor %} {% endblock %} </head> </html>