Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I download the most recent uploaded file from the django admin?
I'm trying to create a efficient way to download the most recently uploaded file from the django admin. The idea is that every month or so, I go in the django admin and upload a excel file. That file will later be downloaded using a button (easy stuff). But what I have now (which isn't efficient), is that every month I upload a file and change the path from the button. This requires understanding of basic html and django, which my users wont understand. To summarize the idea, here is a list: Upload a file every month or so Have the button in html download the most recent file added (automatically) I have thought of many things, like for example having a timestamp set when uploading the file, and have the button download the file with the most recent "date created". But, I couldn't get that to work, and even if I did, would that be an easy/recommended way of doing this? I have also thought of the ability for one to rename the file, but again, you'd need to have a basic understanding of the django admin, which isn't what I want my users to have to do. Is … -
how to add a course to user courses list after payment in django
Imagine you have a store selling training courses. You want to add a course to the list of user-purchased courses. Assuming the purchased course ID is 3, how should we add it to the list of purchased user courses? What method should be used? I tried these code: purchased_course = Course.objects.get(id=3) # for example user_courses_list = request.user.profile.courses.all() user_courses_list.append(purchased_course) but this code didnt work... -
Is it right way to make a copy of instance in Django rest framework?
The main aim is to create a duplicate of the existing document with the same content but different titles. To achieve this, I decided to implement another serializer with the custom create method. I have to modify the view class and dynamically determine what kind of endpoint was called to choose the appropriate serializer. My solution works for me, but I doubt that the solution is correct. If you have any idea about this please tell me. Thank you in advance for sharing your experience. I had the following at the beginning (before modification): model.py ... class Document(models.Model): title = models.TextField('name', unique=True) content = models.TextField('content', default='') view.py ... class DocumentViewSet(viewsets.ModelViewSet): queryset = Document.objects.all() serializer_class = DocumentSerializer serializer.py ... class DocumentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Document fields = ['id', 'url', 'title', 'content'] url.py ... router = SimpleRouter() router.register(r'documents', views.DocumentViewSet, basename='document') My current solution is to modify the following files like these: serializer.py ... # add new serializer class DuplicateDocumentSerializer(serializers.HyperlinkedModelSerializer): parent = serializers.HyperlinkedRelatedField(view_name='document-detail', queryset=Document.objects.all(), write_only=True) content = serializers.ReadOnlyField() def create(self, validated_data): title = validated_data.get('title') parent_doc = validated_data.get('parent') content = parent_doc.content doc = super().create({ 'title': title, 'content': content, }) doc.save() return doc class Meta: model = Document fields = ['id', 'url', 'title', 'content', … -
If I have two Django projects that need to be hosted in separate locations, what is the simplest way to share database information?
A client wants a CMS and a website, both for handling customers (client handles customers onsite as well as online). Here's the tricky part. He wants the CMS onsite, as only employees will be using it, and he wants the website to be hosted online (such as namecheap). Since both of these will have a lot of common information (such as items, prices, customer information), what is the best way to handle this at the database level? Is it ridiculous to sync every 15-30 minutes for example if I put two separate databases? Is it best to have one database and have the other system connect to it? How secure can I make that? -
Updating ManyToMany of a custom user DRF best practice
I've been struggling to understand how one would update a M2M-field in the django rest framework that is between a custom user and some random field. I should mention I'm using Djoser as authentication. Lets say I have a custom user Models: class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) paying_user = models.BooleanField(default=False) subscribed_companies = models.ManyToManyField('myapp.Company') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserAccountManager() def __str__(self): return f"{self.email}' account" class Company(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Meta: ordering = ['name'] My serializers Imports - serializers.py: from django.contrib.auth import get_user_model from djoser.serializers import UserCreateSerializer from rest_framework import serializers from apartments.models.company_model import Company User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('email','password', 'paying_user', 'subscribed_companies') class UserCompanyListSerializer(serializers.ModelSerializer): #Is this a reasonable way to serialize a M2M-field? subscribed_company_ids = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=Company.objects.all(), source='subscribed_companies') class Meta: model = User fields = [ 'subscribed_company_ids' ] class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name',) As you can see, I've attached a M2M-field on the custom user itself, instead of using a OneToOne-field where I store custom data. I'm not sure this is the best way to do it. The idea is that a user should … -
Redirects behind Apache ReverseProxy
My Setup I have an apache2 (2.4 on ubuntu server) webserver which should serve a django and a ruby webapplication on: Ruby: localhost:7000 Django: localhost:8000 Django static files: localhost:9000 All requests are passed to the ruby application, but those with /django/ in front. Another server is serving the static files under /static/. My basic VirtualHost settings <VirtualHost *:443> ServerAdmin some@email ServerName example.com DocumentRoot /var/www/html # Logging SSLEngine On # SSL Certificates SSLOptions +StdEnvVars RequestHeader set X_FORWARDED_PROTO 'https' ProxyPass /django/ http://localhost:8000/django/ ProxyPassReverse /django/ http://localhost:8000/django/ ProxyPass /static/ http://localhost:9000/static/ ProxyPassReverse /static/ http://localhost:9000/static/ ProxyPass / http://localhost:7000/ ProxyPassReverse / http://localhost:7000/ <Location /> ProxyHTMLURLMap "http://localhost:7000" "/" ProxyPassReverse "/" </Location> </VirtualHost> Excuse I had to include the ProxyHTMLURLMap, because when my ruby application got a POST I was redirected to localhost:7000, which is not reachable from the outside. I seems to do what I want it to do, but I am quite unsure about it. The problem My Django application does redirect to an external website, with https://externalsite.com/somesite.php?added=load which is now redirected to https://example.com/somesite.php?added=load I would really appreciate if someone shed a bit of light on the subject. -
Django - order_by multiple related fields doesn't work
I am trying to order a qs by multiple related fields. I have a User and Credits model. Every User has a related Credits object. I want to rank/order a list of Users based on multiple fields in the Credits object: credits (amount) games_played_count (amount) last_game_credits (amount) Hence, if two players have an equal amount of credits the one with the highest games_played_count wins. If that is the same the one with the highest last_game_credits wins. Models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = NameField(max_length=25, unique=True) class Credits(models.Model): credits = models.IntegerField(default=1000) year = models.IntegerField(default=date.today().isocalendar()[0]) week = models.IntegerField(default=date.today().isocalendar()[1]) games_played_count = models.IntegerField(default=0) last_game_credits = models.IntegerField(null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="credits", on_delete=models.CASCADE) class Meta: unique_together = ('year', 'week', 'user') View: def get_queryset(self): year = self.request.query_params.get('year', None) week = self.request.query_params.get('week', None) if week and year is not None: prefetchCredits = Prefetch('credits', queryset=Credits.objects.filter(year=year, week=week)) rankings = User.objects.prefetch_related(prefetchCredits) \ .annotate(creds=Max('credits__credits'), \ gpcreds=Max('credits__games_played_count'), \ lgcreds=Max('credits__last_game_credits')) \ .order_by('-creds', '-gpcreds', 'lgcreds) return rankings The ordering on a single related field works but not on multiple related fields in order_by(). -
I want to display a simple 'hello' message over the server using django in vscode but it says page not found
I want to display a simple hello in the server but receiving an error as Page not found. here are my code: Analytic_web.urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path(r'jas/', include('website.urls')), path('admin/', admin.site.urls), ] website.urls.py: from django.urls import path from . import views urlpatterns = [ path(r'jas/', views.home, name='home'), ] views.py: from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, '/templates/website/home.html' ) home.html: <h1>Helllllllloooooooooowwwwwwwwwwwww</h1> -
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