Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Strange behavior when sending file to django server in vuejs
When sending my audio files in vuejs I kept getting errors 'the submitted data was not a file, check the encoding type on the form.' So I tried giving it a file directly: let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'}); console.log(file) var audiopost = { id: "11", user: "username", room: "roomOne", "audiofile": file} this.$store.dispatch("audio/createAudio",audiopost); However, when analyzing in Burp the resulting post request, the audiofile field was empty.. Do you have any Idea what is happening ? Thanks for reading ! Empty Audiofield burp request -
How to "skip" submodule declaration on import
Starting with the structure (this is a Django project). root/ app_1/ views.py my_module/ __init__.py submodule/ __init__.py mixins.py I can normally import on app_1/views.py with the full declaration. from my_module.submodule.mixins import MyMixin But I wish to skip declaring submodule. from my_module.mixins import MyMixin I've tried some combinations of from x import y on both __init__.py files in my_module and sub_module but I've only managed to skip the submodules altogether. from my_module import MyMixin I don't love this option because it hides all my files. Is there a way to get it the way I want? -
How to retrieve a stripe subscription id after a checkout session in a django project?
Here is my problem. I made a stripe subscription for my django project, and I used the checkout session method. I would like to retrieve the stripe subscription id, after the payment, to put it on my customer model, so I can make a cancel subscription method for the customer, because the method given by stripe require to have this id : stripe.Subscription.modify( *sub_id*, cancel_at_period_end=True ) or stripe.Subscription.delete(*sub_id*) The problem is that I can't find the id anywhere else than in my stripe account, where I have every informations I can need, but I can't find how to retrieve it through code after the payment has been done. I need to fill the field 'stripe_sub_id' in my customer model so i can make the cancel method work. Here is the method that creates the checkout session @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'http://127.0.0.1:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( success_url=domain_url + 'projets/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'projets/cancelled/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': sub_price_id, 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) And here is my script to activate the session //Get stripe publishable key fetch("/projets/config/") .then((result) => { return result.json(); }) … -
How to populate dropdown menu from Django database
I would like to create two dropdown menus from the data out of a database. I have been struggling with this for the past few hours and have no idea how to fix it. I have imported my CSV file to my database using Jupyter with sqlite3: import pandas as pd import sqlite3 lol = pd.read_csv('LeagueofLegends.csv') del lol['Address'] path = '#path to directory' cxn = sqlite3.connect(path + 'db.sqlite3') cxn.cursor().executescript('drop table if exists lol;') lol.to_sql('lol', cxn, index = False) cxn.close() As far as I know, everything went well, but now I'm at the point where I want to make a few dropdown menus from the data from the database. Down below I have included a snippet of the data. The two dropdowns I want to create are a blueTeamTag and a redTeamTag dropdown. I have tried this for hours but have no clue how to do this. Also, both the blueTeamTag and the redTeamTag contain duplicated, that I have to get rid of before putting it in a dropdown. I also included my views.py, models.py, and the HTML script where the dropdown menus should go. views.py: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import Lol # Create … -
What's wrong with my Django Nginx configuration?
I've been having this issue for over the last two months, having deployed using multiple different platforms various times. I am at my wits end. So I am trying to deploy a website using Django, NGINX, GUNICORN to digital ocean. I keep getting a 404 error and have no idea what to do. Settings.PY File Django settings for django project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import mimetypes mimetypes.add_type("text/css", ".css", True) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['mysite.net','wwww.mysite.net','localhost',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], … -
Created objects are not save through cmd in django python
from sabin.models import Task >>> Task.objects.all() <QuerySet []> >>> t=Task(title="dhiraj") t=Task(title="dhiraj") t.save() error says Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: table sabin_task has no column named title The above exception was the direct cause of the following exception: Traceback (most recent call last): File "", line 1, in File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 906, in _do_insert return manager._insert( File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\sql\compiler.py", line 1410, in execute_sql cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, … -
Django On-Insert trigger
I have a model in Django which I want to be automatically populated with values once another model has objects inserted. This is the originator model Question: class Question(models.Model): question = models.CharField(max_length=200, null=False, blank=False) description = models.TextField('description', default=False) voters = models.ManyToManyField(User, related_name='+') votes = models.IntegerField(default = 0) created_by = models.ForeignKey(User, on_delete=models.CASCADE) Question View: class QuestionApiView(AuthenticatedAPIView): """ Lists all questions or creates a new question """ def post(self, request, format=None): vote_data = request.data vote_data["created_by"] = request.user.id data["created_by"]=request.user.id print(vote_data) print(vote_data["voters"]) voter_data = vote_data["voters"] result, valid = QuestionHelper.createQuestion(vote_data) Question Helper: class QuestionHelper(object): @classmethod def createQuestion(klass, questiondata): """ creates a question """ createdQuestion = QuestionSerializer(data=questiondata) if createdQuestion.is_valid(): createdQuestion.save() return createdQuestion.data, True return createdQuestion.errors, False Question Serializer: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' This is my Choice model which I want the values Yes, No and Abstain added onto choice_text once a Question object is created: question = models.ForeignKey(Question, on_delete=models.CASCADE, default=1) choice_text = models.CharField("choice", max_length=250) This way, each Choice will be linked to a Question using the question_id -
Couldn't find that process types (web)
I was trying to host my django app on heroku when I saw the error stating web processes are not working so when searched for I saw that I have to use command: heroku ps:scale web=1 after that I got error: (djangoProject1) C:\Users\USER\PycharmProjects\djangoProject1>heroku ps:scale web=1 Scaling dynos... Couldn't find that process type (web). -
Django see all user information in admin panel
After creating the member record in the application, only the username is reflected in the admin panel, but I want to get the name and surname as well. I specify this in the codes, but there is no reflection. views.py from django.shortcuts import render,redirect from .forms import RegisterForm from django.contrib.auth.models import User from django.contrib.auth import login from django.contrib import messages def register(request): form=RegisterForm(request.POST or None) if form.is_valid(): name=form.cleaned_data.get("name") lastname=form.cleaned_data.get("lastname") username=form.cleaned_data.get("username") password=form.cleaned_data.get("password") #newUser=User(name=name) newUser = User(username=username) newUser.set_password(password) newUser.save() login(request,newUser) messages.info(request,"Başarıyla Kayıt Oldunuz...") return redirect("index") context={ "form":form } return render(request,"register.html",context) Form.py from django import forms from django.contrib.auth.forms import UserCreationForm class RegisterForm(forms.Form): name=forms.CharField(max_length=50,label="Adı ") lastname=forms.CharField(max_length=50,label="Soyadı ") username=forms.CharField(max_length=50,label="Kullanıcı Adı ") password=forms.CharField(max_length=20,label="Parola",widget=forms.PasswordInput) confirm=forms.CharField(max_length=20,label="Parolayı Doğrula ",widget=forms.PasswordInput) def clean(self): name=self.cleaned_data.get("name") lastname=self.cleaned_data.get("lastname") username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") confirm=self.cleaned_data.get("confirm") if password and confirm and password != confirm: raise forms.ValidationError("Parolalar Eşleşmiyor...") values = { "name" : name, "lastname" :lastname, "username" : username, "password" : password, } return values Although I specify the name and name fields, it is not reflected in the panel -
How to assign a user to a new object with Django?
I'm trying to assign the current logined user to an account model object in Django but for some reason the user is not assigned. I did try with form.user = User.objects.get(username=request.user) but problem is the same. How could I do that ? This is my code, a logged in user is able to create a new instance of the model but instance.user remains empty. models.py class Account(models.Model): name = models.CharField(max_length=100, null=True, blank=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True ) forms.py class AccountForm(ModelForm): class Meta: model = Account fields = ['name'] view.py def create_account(request): if request.method == 'POST': form = AccountForm(request.POST) if form.is_valid(): form.user = request.user print('user', request.user) # Return the user name correctly form.save() return redirect('accounts') else: form = AccountForm() return render(request, 'account/account_create.html', { 'form': form }) account_create.html <h1>Create new account</h1> <form action="{% url 'account_create' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button class="button" type="submit">Create</button> </form> -
Django page not found (404) error I think there is some mistake in urls and in edit.html in forms action
enter image description hereThis is my edit.html <form method="POST" action="update/{{i.id}}" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="noticeperiod">Notice Period (in Days) :</label> <input type="text" class="form-control" value ={{i.noticeperiod }} name="noticeperiod" id="notice_period" placeholder="Notice Period"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="preferredlocation">Current Location :</label> <input type="text" class="form-control" value ={{i.preferredlocation}} name="preferredlocation" id="preferred_location" placeholder="Enter Current Location"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="expectedlocation">Expected Location :</label> <input type="text" class="form-control" value ={{i.expectedlocation}} name="expectedlocation" id="expected_location" … -
How to trace code in a Django production system
My code behaves different in the production code, than on my development machine. I would like to debug/trace it. Since it runs on Heroku. I use PyCharm. AFAIK I can't insert import pydevd_pycharm; pydevd_pycharm.settrace(... into the code. I don't need a fancy GUI a command-line tool would be fine, too. I would be happy if I could see all lines which get executed during a particular http request. How to solve this for production systems? -
Converting .csv string data into DateField type in Django models.py
I am using Python 3.7 on Debian 10 I have a number of pre-existing .csv files with these columns: first_name, last_name, birthdate, phone, email I am importing them into a postgres database with Django as the framework. My Django model: from django.db import models class User(models.Model): first_name = models.TextField(blank=False, null=False) last_name = models.TextField(blank=False, null=False) birthdate = models.TextField(blank=True, null=True) phone = models.TextField(blank=False, null=False) email = models.TextField(blank=False, null=False) Custom Django Management Command to import file import_users.py: class Command(BaseCommand): def handle(self, *args, **options): users_file = open(f'{settings.DATA_IMPORT_LOCATION}/users.csv', 'r') for counter, line in enumerate(users_file): line_fields = line.split(',') first_name = line_fields[0] last_name = line_fields[1] birthdate = line_fields[2] phone = line_fields[3] email = line_fields[4] u = User() u.first_name = first_name u.last_name = last_name u.birthdate = birthdate u.phone = phone u.email = email u.save() Output sample when running the following Django ORM query : > for u in User.objects.all(): print(u.birthdate) Output: birthdate 2015-05-28 2009-06-14 2007-01-01 2007-02-17 2008-05-16 2013-01-19 2008-07-24 2015-05-01 2007-06-03 2007-01-17 When birthdate = models.TextField is set to TextField, I can import these .csv files into my Postgres database successfully with my management command. This makes sense because all the .csv data are strings. However, I want to correctly set the model to read as a date, … -
What shall I use for full text search and fuzzy search on a social network django site with a postgresql database?
So, I was looking for a search engine for my new django project with a postgresql database and I ended up with elasticsearch and sphinx. I've chosen the second one, because I thought that if you're searching in a lot of posts you need a fast search, which uses less memory, but after looking at realization of sphinx I went up like, "How do I do that on python and can I do fuzzy search with it?". I've found few django-sphinx libraries, but they seem to be abandoned (last update was 5 years ago), and in sphinx documentation I didn't find anything about django, just few mentions of python. So, is sphinx still alive and how can I use it with django, or should I choose another engine for my tasks? -
"Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers." ValueError: Input is not valid
I am using Bert tokenizer for french and I am getting this error but I do not seems to solutionated it. If you have a suggestion. Traceback (most recent call last): File "training_cross_data_2.py", line 240, in <module> training_data(f, root, testdir, dict_unc) File "training_cross_data_2.py", line 107, in training_data Xtrain_emb, mdlname = get_flaubert_layer(data) File "training_cross_data_2.py", line 40, in get_flaubert_layer tokenized = texte.apply((lambda x: flaubert_tokenizer.encode(x, add_special_tokens=True, max_length=512, truncation=True))) File "/home/getalp/kelodjoe/anaconda3/envs/env/lib/python3.6/site-packages/pandas/core/series.py", line 3848, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File "pandas/_libs/lib.pyx", line 2329, in pandas._libs.lib.map_infer File "training_cross_data_2.py", line 40, in <lambda> tokenized = texte.apply((lambda x: flaubert_tokenizer.encode(x, add_special_tokens=True, max_length=512, truncation=True))) File "/home/anaconda3/envs/env/lib/python3.6/site-packages/transformers/tokenization_utils.py", line 907, in encode **kwargs, File "/home/anaconda3/envs/env/lib/python3.6/site-packages/transformers/tokenization_utils.py", line 1021, in encode_plus first_ids = get_input_ids(text) File "/home/anaconda3/envs/env/lib/python3.6/site-packages/transformers/tokenization_utils.py", line 1003, in get_input_ids "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers." ValueError: Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers. I look around to fond answer but whaever is proposed do not seems to work. Texte is dataframe. here the code : def get_flaubert_layer(texte): # teste is dataframe which I take from an excel file language_model_dir= os.path.expanduser(args.language_model_dir) lge_size = language_model_dir[16:-1] # modify when on jean zay 27:-1 … -
Django-easy-maps width and height are not dynamic values
I am trying to integrate django-easy-maps 2.0 in my website, everything works well but the width and height are not dynamic and they don't response with my specific div {% easy_map profile_license.location 375 400 %} look at 375 400 values I want to make them in percentage values but it doesn't work -
Django Running Python Function to Update Page w/o Refresh
I am making a website that tracks population statistics. The site needs to update about every 5 seconds with the latest information. Here is the relevant code for displaying the pandas df on the page (in a file titled "home.html"): {% block content %} <h1>Population Tracker</h1> {% for index, label,data in pop_df.itertuples %} <div class = "row__data"> <p>{{label}}: {{data}}</p> </div> {% endfor %} {% endblock content %} Here is the code for my scraper (in a separate file called "scraper.py") class Scraper(): def __init__(self): self.URL = "https://countrymeters.info/en/Japan" def scrape(self): "Scrapes the population data once" page = requests.get(self.URL) soup = BeautifulSoup(page.content,'html.parser') data_div = soup.find_all('div',class_="data_div")[0] table = data_div.findAll("table")[0] tr = table.findAll('tr') labels = [] numbers = [] for n, i in enumerate(tr): number = i.findAll('td',{"class":"counter"})[0].text # numbers label = i.findAll('td',{"class":"data_name"})[0].text # labels labels.append(label) numbers.append(number) pop_df = pd.DataFrame( { 'Labels':labels, 'Data': numbers } ) return pop_df In my views.py file, here is what I have done: from django.shortcuts import render from bsoup_tracker.scraper import Scraper scraper = Scraper() df = scraper.scrape() def home(request): context = { 'pop_df':df } return render(request,'tracker/home.html',context) Basically, I would like to be able to call the render onto my home.html page every 5 seconds to reupdate the page, without needing … -
Want to display my watchlist contents on a page
I am working on an online e-commerce site and I have an add to watchlist button for each product but I don't know how to display the user's watchlist on a new page This is the model for the products: class Listings(models.Model): Name = models.CharField(max_length=64) seller = models.CharField(max_length=64) current_bid= models.IntegerField() description=models.TextField() time=models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=64) image_link = models.CharField(max_length=200, default=None, blank=True, null=True) #max_bid=models.IntegerField(blank=True,null=True) def __str__(self): return 'Listings: {}'.format(self.Name) This is for the Watchlist model class Watchlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(Listings) This is the view to add the watchlist: @login_required(login_url='/login') def watchlist(request,id): item_to_save=Listings.objects.get(id=id) obj=Watchlist.objects.filter(user=request.user,item=item_to_save) comments=Comments.objects.filter(listingid=id) #query to check if the item already exists in watchlist if obj.exists(): obj.delete() return render(request,"auctions/listing.html",{"item":item_to_save,"added":True,"comments":comments}) else: watchlist_obj=Watchlist(user=request.user) watchlist_obj.save() watchlist_obj.item.add(item_to_save) return render(request, "auctions/listing.html",{"item":item_to_save,"added":False,"comments":comments}) This is the view to show a users watchlist: #view for my watchlist @login_required(login_url='/login') def mywatchlist(request): #gathering a list for the particular user mylist=Watchlist.objects.filter(user=request.user) there:False list_products=[] #if there is a list if mylist: there=True for i in mylist: product=Listings.objects.get(id=i.item) list_products.append(product) return render(request, "auctions/mywatchlist.html", { "product_list": list_products, "present": there}) What I really have a doubt about is how to link the listings to the watchlist (I don't know what item field in the watchlist model really holds. And without sending the id how … -
django-money is not converting correctly
I am using django-money to make conversions on my backend of the project but it is converting wrong. For example, I want to convert TRY to USD: I enter 1000000 TRY it returns 480629.66 USD, but it should be: 120055.20 TRY. How can I solve it? views.py def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = NewCustomerForm(request.POST) # Check if the form is valid: if form.is_valid(): newCustomer = form.save() newCustomer.company = company selected_currency = newCustomer.currency_choice selected_limit = newCustomer.credit_limit newCustomer.usd_credit_limit = convert_money(Money(selected_limit, selected_currency), 'USD') cred_limit = newCustomer.usd_credit_limit value = str(cred_limit)[1:] # float_str = float(value) float_str = float(cred_limit.amount) newCustomer.credit_limit = float_str newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) forms.py class NewCustomerForm(forms.ModelForm): ... class Meta: model = Customer fields = ('customer_name', 'country', 'address', 'customer_number', 'phone_number', 'email_address', 'credit_limit', 'currency_choice', 'risk_rating', 'parent', 'entity') models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ('CAD', 'CAD'), ('CHF', 'CHF'), ('DKK', 'DKK'), ('PLN', 'PLN'), ('HUF', 'HUF'), ('CZK', 'CZK'), ('RUB', 'RUB'), ('KZT', 'KZT'), ('BGN', 'BGN'), ('RON', 'RON'), ('UAH', 'UAH'), ('TRY', 'TRY'), ('ZAR', 'ZAR'), ] .... currency_choice … -
Django - Edit access only if logged in user is the user who added the item or if he is a superuser
I am working on a rental website project where users can create a login and add a listing. Now I want the edit access to be given to only the owners of those listing and superuser. I am able to set the edit access either to superuser or to the user, I am trying to figure out how to do both. models.py class Listing(models.Model): category = models.ForeignKey( 'Category', null=True, blank=True, on_delete=models.SET_NULL) listing_name = models.CharField(max_length=250, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) price = models.CharField(max_length=250, null=True) short_description = models.CharField(max_length=720) description = models.TextField() bedroom = models.CharField(max_length=250, null=True, blank=True,) bathroom = models.CharField(max_length=250, null=True, blank=True,) lease = models.CharField(max_length=250, null=True, blank=True) contact_name = models.CharField(max_length=250, null=True) email_address = models.CharField(max_length=250, null=True) contact_number = models.CharField(max_length=12, null=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) image_one = models.ImageField(null=True, blank=True) image_two = models.ImageField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.listing_name views.py @login_required def edit_listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) if not request.user.is_superuser or request.user == listing.user: messages.error( request, 'Sorry, you dont have the permission to do that.') return redirect(reverse('home')) if request.method == 'POST': if request.user == listing.user: form = ListingForm(request.POST, request.FILES, instance=listing) if form.is_valid: form.instance.user = request.user form.save() messages.success(request, 'Successfully updated the listing') return redirect(reverse('listing_detail', args=[listing.id])) else: messages.error( request, 'Failed … -
creating django project executable or setup file with postgree
Hello Guys is there anyone know How to convert (python v 3.7) django project in a setup file or executable file with using postgree database i'm trying convert using pyinstaller but getting error of settings.py installed apps not found pls join this discussion if anyone know about it. -
IntegrityError at /contact NOT NULL constraint failed: first_contact.fname
getting an integrity error while running this code. Also after some modifications in models.datefield(), it went well but the data base was not storing the entries and the table was empty when the forms were filled. models.py # Create your models here. class Contact(models.Model): fname = models.CharField(max_length=50) lname = models.CharField(max_length=122) desc = models.TextField() city = models.CharField(max_length=20) phone = models.CharField(max_length=12) date = models.DateField() here is my views.py from datetime import datetime from first.models import Contact # Create your views here. def index(request): return render(request, 'index.html') # return HttpResponse("This is our home page") def about(request): return render(request, 'about.html') #return HttpResponse("This is our about page") def services(request): return render(request, 'services.html') #return HttpResponse("This is our services page") def contact(request): if request.method == "POST": fname = request.POST.get('fname') lname = request.POST.get('lname') desc = request.POST.get('desc') city = request.POST.get('city') phone = request.POST.get('phone') contact = Contact(fname=fname, lname=lname, desc=desc, city=city, phone=phone, date=datetime.today()) contact.save() return render(request, 'contact.html') #return HttpResponse("This is our contact page") -
In django i got AttributeError: module 'django.contrib.admin' has no attribute 'display'
from django.contrib import admin from .models import Shop @admin.register(Shop) class ShopAdmin(admin.ModelAdmin): @admin.display(description='Name') def upper_case_name(self,obj): return("%s" % (obj.name)).upper() -
why model function created on django 3.1.10 doesn't Work on 3.2?
i created a proxy model in django 3.1.10 where i defined a function to make a copy of an object with all it's related objects through foreign key and it worked fine , but when i upgraded to django 3.2 the function only create a copy of the object without any related objects from django.db import models from django.utils import timezone from django.contrib.auth.models import User from ValPlanner.models import ProgramExecution import datetime from django.utils import timezone #----------------------------------------------------------------------------------------------------------------------------- class Record(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=200) execution = models.ForeignKey(ProgramExecution, on_delete=models.PROTECT,null=True) timestamp = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, on_delete=models.PROTECT) record_type = models.CharField(max_length=50,default='template') def __str__(self): return self.title class TemplateRecord(Record): class Meta: proxy = True def create_report(self,creator,execution): stages = self.stage_set.all(); self.record_type = 'record' self.pk = None; self.execution = execution self.creator = creator self.save(); for stage in stages : samples = stage.sample_set.all() stage.pk = None stage.stage_type = 'record' stage.record = self stage.save(); for sample in samples : tests = sample.testnum_set.all() sample.sample_type = 'record' sample.stage = stage sample.sample_time = timezone.now() sample.sampler = creator for samplenum in range(sample.number_of_samples): sample.pk = None sample.save(); for test in tests : test.pk = None test.test_type = 'record' test.sample = sample test.tester = creator test.save(); #----------------------------------------------------------------------------------------------------------------------------- class Stage(models.Model): record = models.ForeignKey(Record, on_delete=models.CASCADE) title = … -
Passing arguments to Django CBV for queryset
I'm trying to figure out how can I pass arguments from a generic view where a user submits a form to a cbv template view. My first generic view is as such: def homepage(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): form_data = form.cleaned_data return redirect('filtered', city=form_data['city'], category=form_data['category']) else: form = SearchForm() return render(request, 'index.html', context={'form': form}) What Im trying to achieve is that when a user choses a city and a category then he gets submitted to a homepage that is a TemplateView where there's a queryset based on objects that are in the selected city and of selected category. class ListAd(ListView): model = Ad template_name = 'filtered' queryset = # here Im expecting to make a query based on the 'city' and 'category' chosen in previous view How to pass the city and category arguments to the ListAd view so I can use them in the queryset? This is the ursl.py urlpatterns = [ path('list_new/<city>/<category>/', views.ListAd.as_view(), name='filtered'), ] Any help would be appreciated. Thank you