Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "rootuser" does not exist
`I am trying to connect deploy a django backend with postgres db on digitalocean droplet. but it's giving me this error after after gunicorn and nginx setup: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "rootuser" does not exist rootuser is my root username not the db username, my db username is dbadmin i tried to create db user with name serveroot, it worked but started throwing other errors `relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... -
Error: (Internal server error) Django apache2 - mod_wsgi
I'm trying to deploy my django application on my remote server, but I'm getting an http 500 internal server error. Here are the configurations I made: Fichier 000-default.conf <VirtualHost *:80> WSGIDaemonProcess myproject python-home=/home/ubuntu/project/env python- path=/home/ubuntu/project/my_project WSGIProcessGroup myproject WSGIScriptAlias / /home/ubuntu/project/my_project/wsgi.py <Directory /home/ubuntu/project/my_project> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Error log [Fri Dec 30 11:28:18.988904 2022] [wsgi:error] [pid 31289:tid 140473618372288] [remote 41.82.143.41:50428] File "/home/ubuntu/project/my_project/wsgi.py", line 12, in <module> [Fri Dec 30 11:28:18.988915 2022] [wsgi:error] [pid 31289:tid 140473618372288] [remote 41.82.143.41:50428] from django.core.wsgi import get_wsgi_application [Fri Dec 30 11:28:18.988933 2022] [wsgi:error] [pid 31289:tid 140473618372288] [remote 41.82.143.41:50428] ModuleNotFoundError: No module named 'django' [Fri Dec 30 11:28:19.164861 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] mod_wsgi (pid=31289): Failed to exec Python script file '/home/ubuntu/project/my_project/wsgi.py'. [Fri Dec 30 11:28:19.164958 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] mod_wsgi (pid=31289): Exception occurred processing WSGI script '/home/ubuntu/project/my_project/wsgi.py'. [Fri Dec 30 11:28:19.165130 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] Traceback (most recent call last): [Fri Dec 30 11:28:19.165172 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] File "/home/ubuntu/project/my_project/wsgi.py", line 12, in <module> [Fri Dec 30 11:28:19.165183 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] from django.core.wsgi import get_wsgi_application [Fri Dec 30 11:28:19.165212 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] ModuleNotFoundError: No … -
how ManyToManyField works?
i made a genre field for my model in a music project ,i could use ForeignKey too pick genres in create section ,but in order to add another part(genres list) to site i used manytomany field since it works reverse ,i thought maybe i can add a genres part that when you click on genre like pop it shows a list of musics that has pop in their genres list ? i wonder if its possible to do this ,if its is can you please a little guide me class Musics(models.Model): #posts model name = models.CharField(max_length=200) band = models.CharField(max_length=200) release = models.DateField() genres = models.ManyToManyField('Genres',related_name='genres_relation') user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) class Meta(): ordering = ['release'] verbose_name = 'Music' verbose_name_plural = 'Musics' def __str__(self): return self.name def get_absolute_url(self): return reverse('pages:music_detail',args=[str(self.id)]) #class Tags(models.Model): #tags model #tag_name = models.CharField(max_length=100) class Genres(models.Model): #Genres model genre_name = models.CharField(max_length=100) class Meta(): ordering = ['genre_name'] verbose_name = 'Genre' verbose_name_plural = 'Genres' def __str__(self): return self.genre_name -
'React is not defined' when installing component library that I'm trying to create using Rollup and React
I'm trying to create a React component library. I'm using Rollup for bundling the files. I'm generating build folder then running npm pack to get a .tgz file of the library. Then I'm installing that file in another project using file:filename.tgz and npm install. But when I run the server it shows me ReferenceError: React is not defined. I assume this is happening because React is not included in the component library. rollup.config.js import { babel } from "@rollup/plugin-babel"; import resolve from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import terser from "@rollup/plugin-terser"; import peerDepsExternal from "rollup-plugin-peer-deps-external"; import sourcemaps from "rollup-plugin-sourcemaps"; const packageJson = require("./package.json"); const config = { input: "src/index.js", output: [ { file: packageJson.main, format: "cjs", }, { file: packageJson.module, format: "esm", }, ], plugins: [ sourcemaps(), babel({ presets: [ [ "@babel/preset-react", { runtime: "automatic", }, ], ], plugins: ["@babel/plugin-transform-runtime"], babelHelpers: "runtime", }), resolve(), commonjs(), terser(), peerDepsExternal(), ], globals: { react: "React", }, }; export default config; package.json { "name": "@rahul-wos/pkg-practice", "version": "1.0.2", "description": "This is my first try at generating a component library", "main": "dist/cjs/index.js", "module": "dist/esm/index.es.js", "type": "module", "files": [ "dist" ], "scripts": { "rollup": "rollup --bundleConfigAsCjs -c ", "pack": "rollup --bundleConfigAsCjs -c" }, "author": "Rahul Patil", "license": … -
AttributeError: 'Order' object has no attribute 'shipping'
Learning Django with https://www.youtube.com/watch?v=woORrr3QNh8&list=PL-51WBLyFTg0omnamUjL1TCVov7yDTRng&index=22. In the end of lesson I have error: AttributeError: 'Order' object has no attribute 'shipping'. I cant understand whats wrong. Error I understand than 'Order' must have 'shipping' attribute, but cant find where exactly looking that. Sorry for bad english. My progect files: project checkout.html from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_addet = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, … -
Django get queryset fail on unmanaged database
I'm trying to use Django's ORM on a read-only database. Here is the model used: class Languages(models.Model): idlanguage = models.IntegerField(primary_key=True) language = models.CharField(max_length=50) code = models.CharField(max_length=50) class Meta: managed = False db_table = 'languages' The configuration of the database part in the settings.py file : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'XXXXXXX', 'USER': 'XXX', 'PASSWORD': 'XXXXXXXXXXXXXXXXXXXXX', 'HOST': '', 'PORT': '', }, 'ro_bdd': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'XXXXX', 'USER': 'XXXXXXXXXX', 'PASSWORD': 'XXXXX', 'HOST': 'XXXXXXXXX', 'PORT': 'XXXX', } } And querysets : In [1]: Languages.objects.all().using("ro_bdd") Out[1]: <QuerySet [<Languages: Languages object (1)>]> In [2]: Languages.objects.filter(idlanguage=1).using("ro_bdd") Out[2]: <QuerySet [<Languages: Languages object (1)>]> In [3]: Languages.objects.get(idlanguage=1).using("ro_bdd") /....../python3.9/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 82 return self.cursor.execute(sql) 83 else: ---> 84 return self.cursor.execute(sql, params) 85 86 def _executemany(self, sql, param_list, *ignored_wrapper_args): ProgrammingError: ERROR: relation « languages » does not exist LINE 1: ..., "languages"."language", "languages"."code" FROM "languages... ^ Values : 'sql' => SELECT "languages"."idlanguage", "languages"."language", "languages"."code" FROM "languages" WHERE "languages"."idlanguage" = %s LIMIT 21 'params' => (1,) Why the get queryset does not work ? -
Why dajngo Is asking me password 3 times in a custom User model Singup
Hi I think I messed up my custom User creation system. Time ago it works fine but I dont know what I did, and it ended messed up. Now in order to create a new user 3 PASSWORDS fiels are required I have a custom user model that uses email instead of username like this: from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username = None email … -
I'm a beginner and I didn't understand about get_absolute_url
I'm very new on django I was follow this guide models.py from django.db import models class GeeksModel(models.Model): title = models.CharField(max_length = 200) description = models.TextField() def __str__(self): return self.title views.py from django.views.generic.edit import CreateView from .models import GeeksModel class GeeksCreate(CreateView): model = GeeksModel fields = ['title', 'description'] urls.py from django.urls import path from .views import GeeksCreate urlpatterns = [path('', GeeksCreate.as_view() ),] geeksmodel_form.html <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form.as_p }} <input type="submit" value="Submit"> </form> page screenshot: After submit button on page "geeksmodel_form.html", I get error get_absolute_url. How to fix it? -
IntegrityError at /create NOT NULL constraint failed: myapp_post.author_id
I want to make the author and user profile the same, but I am getting an error while creating it, I would appreciate it if you could help, also if you could help me connect the author and user profile My View: @login_required(login_url='accounts/login') def create(request): if not request.user.is_authenticated: return Http404 form=PostForm(request.POST or None) if form.is_valid(): post=form.save(commit=False) post.user=request.user post.save() messages.success(request,'Başarılı bi şekilde Oluşturdunuz!') return HttpResponseRedirect(post.get_absolute_url()) context={'form':form} return render(request,'blog/form.html',context) My Post Model: class Post(models.Model): author=models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE,verbose_name='Kullanıcı') title=models.CharField(max_length=100,verbose_name='başlık') content=models.TextField(verbose_name='Açıklama') date=models.DateTimeField(auto_now_add=True) image=models.ImageField(null=True,blank=True) slug=models.SlugField(unique=True,editable=False) My UserProfile: class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile') username=models.CharField(verbose_name='Kullanıcı Adı',max_length=40,null=True,blank=True) name=models.CharField(verbose_name='ad',max_length=40,null=True,blank=True) surname=models.CharField(verbose_name='Soyad',max_length=40,null=True,blank=True) bio=models.TextField(null=True,blank=True) avatar=ResizedImageField(null=True,blank=True,size=[300,300]) Error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create Django Version: 4.1.3 Python Version: 3.11.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'crispy_forms', 'accounts'] Installed 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'] Traceback (most recent call last): File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: myapp_post.author_id) was the direct cause of the following exception: File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\tr\Documents\django-project\yeter\myapp\views.py", line 32, in create … -
Objects have the same ID on production in Django App
I have project in Python Django. It has three models: Project, Files and Agreement. class Project(models.Model): project_name = models.CharField(max_length=50) client_name = models.CharField(max_length=50) agreement_number = models.CharField(max_length=20) brief_status = models.CharField(max_length=20, choices=BRIEF_CHOICES, default='nieuzupelniony') agreement_status = models.CharField(max_length=20, choices=AGREEMENT_CHOICES, default='niedostarczona') resources_status = models.CharField(max_length=20, choices=RESOURCES_CHOICES, default='niedostarczone') payment_status = models.CharField(max_length=20, choices=PAYMENT_CHOICES, default='nieoplacone') message = models.CharField(max_length=200, default='Brak wiadomości') project_date = models.CharField(max_length=10) status = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="project") modifications = models.CharField(max_length=15, default='2') corrections = models.CharField(max_length=15, default='3') def __str__(self): return self.project_name class Files(models.Model): name = models.CharField(max_length=50) upload = models.FileField(upload_to='uploads/', validators=[validate_file_extension]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="files") project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name class Agreement(models.Model): name = models.CharField(max_length=50) upload = models.FileField(upload_to='uploads/', validators=[validate_file_extension]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="agreement") project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name In app we have an admin and users. Every user has welcome.html page which display every user project, every user agreement and objects from one additional model which isn't important. When user click on project (user goes to project_detail.html), he can see information about project and there are all files from this project. def panel(request): if request.user.is_authenticated: queryset = Project.objects.filter(user=request.user) queryset2 = Invoice.objects.filter(user=request.user) queryset3 = Files.objects.filter(user=request.user) queryset4 = Agreement.objects.filter(user=request.user) return render(request, 'projects/welcome.html', {'project': queryset, 'invoice': queryset2, 'files': queryset3, 'agreement': queryset4}) else: return render(request, … -
linking apps in Django, which is better, urls.py or app.py?
Going through some tutorials as a beginner in Django, I noticed a tutor linked the various apps in the urls.py and another tutor did it with the app.py using the config function just looking for clarification before I try anything -
Django download a file with a wrong utf-8 encoder
I trying to make an api to download file from server folder but have some problem with encoder. This is my code: @login_required(redirect_field_name="next",login_url='login_form') def downloadMachineLog(request): if(request.method == "GET"): fileName = request.GET.get('fileName') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filePath = BASE_DIR+"\\reminder\\log\\"+fileName file_is_exists = exists(filePath) print(filePath) if(file_is_exists): with open(filePath,'r',encoding='utf-8-sig') as file: mime_type,_ = mimetypes.guess_type(filePath) response = HttpResponse(file,content_type = mime_type+"charset=utf-8-sig") response['Content-Disposition'] = "attachment; filename=%s" % fileName return response else: return HttpResponse("This log is not exists") else: return HttpResponse("Error") The log file was generated using "utf-8-sig" encode. It can read fine on the server side. But if the file is downloaded from the client side the encode is wrong and shows unexpected text. I need to download the file and be able to keep the encoder properly. what was I missing? -
i want to hide reconcile_type if can_reconcile == False in Django
class ApiConfiguration(models.Model): CURRENCIES = ( ('AE', 'AED'), ('SA', 'SAR'), ('QA', 'QAR'), ('OM', 'OMR'), ('BH', 'BHD'), ('KW', 'KWD'), ('EG', 'EGP'), ('IN', 'INR'), ('US', 'USD'), ('UK', 'GBP'), ('TR', 'TRY'), ) RECONCILE_TYPES = ( ('excel', 'Upload Excel'), ('api', 'API Call'), ) name = models.CharField(max_length=255, unique=True) code = models.CharField(max_length=10, unique=True) endpoint = models.TextField( null=True, blank=True, verbose_name='Endpoint/Base URL') username = models.TextField( null=True, blank=True, verbose_name='API Username') password = models.TextField( null=True, blank=True, verbose_name='API Password') config_details = models.TextField(null=True, blank=True) account_balance = models.TextField(null=True, blank=True) balance_currency = models.CharField( max_length=3, choices=CURRENCIES, null=True, blank=True) can_check_status = models.BooleanField() can_check_balance = models.BooleanField() can_reconcile = models.BooleanField() reconcile_type = models.CharField( max_length=20, null=True, blank=True, choices=RECONCILE_TYPES) has_brand_catalogue = models.BooleanField() has_expiry = models.BooleanField() can_cancel = models.BooleanField() how can i do it without using any j query ,i have tried some django forms , i dont know anything more about this topic how can i do it without using any j query ,i have tried some django forms , i dont know anything more about this topic how can i do it without using any j query ,i have tried some django forms , i dont know anything more about this topic how can i do it without using any j query ,i have tried some django forms , i … -
How do I add a placeholder on a FileField in Django?
I tried creating placeholder by using the following code: class ReceiptsForm(forms.ModelForm): class Meta: model = Receipts fields = ('receipt',) widgets = { 'receipt' : forms.FileInput(attrs={'class': 'form-control', 'placeholder': 'Maximum 3 files allowed.'}), } And then rendering by using the following snippet in the template: <form action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <button type="submit" class="btn btn-sm btn-primary mt-1">Submit</button> </form> But still the placeholder text is not appearing besides the fileinput. -
I am manually generating a form in django(3.1.2) framework, but the name and type field are empty while rendering form
<div class="col-sm-9"> <input type="{{ widget.type }}" class="form-control mt-3" id="{{form.Address.id_for_label}}" name="{{ widget.name }}" {% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %} /> </div> name and type field are empty. so i cannot pass the form data to request.POST. <div class="col-sm-9"> <input type="" class="form-control mt-3" id="id_Address" name="" /> </div> -
Django app with Azure AD account identity provider deployment to Azure Web app service fails
Background I am trying to deploy a Django web app with Azure AD as the account identity provider to Azure Web app services following the Microsoft tutorial. My app is registered on the Azure AD portal. It works well in development on localhost. Problem However, when i deploy it to Azure Web app services, it fails because it requests a redirect URI starting with http while Azure AD requires that any non localhost server must have a redirect URI starting with https. Specifically, it requests a redirect URI as http://myapp.com/auth/redirect. But, i am only allowed to register URI https://myapp.com/auth/redirect in Azure AD. This problem was addressed in a related Stackoverflow question The solution given was to "Run server with ./manage.py runserver_plus --cert /tmp/cert localhost:8000". This works great on localhost, but i am having trouble deploying it to Azure web app service. My deployment file stored in .github/workflows/deploy_on_<myapp>.yml has the deploy job defined as follows: deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: python-app path: . - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 id: deploy-to-webapp with: app-name: 'fno-calculator' slot-name: 'Production' publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_<secret> … -
How to get django session data with javascript?
i save session data in django with key 'theme' : request.session['theme'] = 'light' Then i want to get 'theme' session data in javascript with this code: sessionStorage.getItem("theme"); but i can't get theme data. How can I do this? -
Ordering of related models by a field
I'm stuck in the ordering of a queryset and looking here for inputs I have two models such as - class Groups(models.Model): participants = models.ManyToManyField(User, related_name='group_member') def __str__(self): return str(self.id) and the second one as - class GroupViews(models.Model): group = models.ForeignKey(Groups, related_name="abc", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) I have to sort Groups in the reverse order of timestamp - (latest first) My approach till now - First way - grps = Groups.objects.filter(participants__id = userId) orderedGrp = grps.order_by("-abc__timestamp").distinct() .distinct() doesn't work here and I get multiple instances because Groups is used as one-to-many in GroupVIews Second way - grps = Groups.objects.filter(participants__id = userId) da = [] //get the last element because timsestamp depends on last for each in grps: da.append(GroupViews.objects.values_list("id", flat=True).filter(group = each).last()) //get the orderer values of Group from here orderedValues = GroupViews.objects.values_list("group", flat=True).filter(id__in = da).order_by('-timestamp') // here I have ordered Id of Groups, How can I run a query to get Groups in the same order ( values of OrderValues) Anyone ? Thanks!! -
Not getting the required interface everytime i search using/admin ,
I am following a yt tutorial on django(https://www.youtube.com/watch?v=sm1mokevMWk) where the tutor searches http://127.0.0.1:8000/admin and gets the required interface (It starts around 49:00) everytime i search http://127.0.0.1:8000/admin i get a DoesNotExist at /admin but when i search http://127.0.0.1:8000/admin/login/?next=/admin/nw/ i get the required interface A question exactly same as mine has been asked before but the thing is i did not make the same error as that person did this is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList,Items def index(response,name): ls=ToDoList.objects.get(name=name) item=ls.items_set.get(id=1) return HttpResponse("<h1>%s</h1><br></br><p>%s</p>"%(ls.name,str(item.text))) # Create your views here. this is my urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.url")), ] this is my models.py from django.db import models class ToDoList(models.Model): name=models.CharField(max_length=200) def __str__(self): return self.name class Items(models.Model): todolist=models.ForeignKey(ToDoList,on_delete=models.CASCADE) text=models.CharField(max_length=300) complete=models.BooleanField() def __str__(self): return self.text -
How to use autocomplete-light with taggit?
What's suggested in the documentation doesn't work, so it can be assumed that no documentation exists. I tried what it suggests: models.py from django.db import models from taggit.managers import TaggableManager class SomeModel(models.Model): name = models.CharField(max_length=200) tags = TaggableManager() def __str__(self): return self.name views.py from dal import autocomplete from taggit.models import Tag class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Tag.objects.none() qs = Tag.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs which doesn't work and results in an empty query set with an authenticated user. To be fixed, Tag.objects has to be changed to SomeWorkingModel.objects. Followed by registering endpoints: path( 'some-model-autocomplete/$', SomeModelAutocomplete.as_view(), name='some-model-autocomplete', ), which works fine when reversed or queried in browser. Then I place a TagField in the form: tags = TagField(label='', widget=TaggitSelect2('some-model-autocomplete')) and in the template, I include these at the end <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> {{ form.media }} The result: a useless, large text area in the middle of the form that doesn't do or respond to anything. I don't care if a solution exists in assembly language as long as it works and it can be proven it works with this setup, suggestions for alternatives … -
TypeError when creating superiser in Django using custom users app
I am building a custom users app in Django for the web application I am making and tried to create a superuser (using this command: python manage.py createsuperuser), I added the username, email and phone number but when I enter the password (letters and numbers) I got the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/john/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/john/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/john/venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/john/venv/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/home/john/users/models.py", line 47, in create_superuser return self._create_user(username, phone_number, email, password, True, True, **extra_fields) File "/home/john/users/models.py", line 29, in _create_user user.set_password(password) File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 99, in set_password self.password = make_password(raw_password) File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/hashers.py", line 79, in make_password % type(password).__qualname__ TypeError: Password must be a string or bytes, got int. this is the model.py script for the users model import random from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core import validators from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, … -
I am creating an jobsearch website in django. where jobseekers can find jobs and recruiters can post the jobs,
I have three diffrent apps in my django project, Home, jobseeker and recruiter. and each app have different subdomain. Home => localhost:8000, jobseeker => jobseeker.localhost.8000, and for recruiter => recruiter.localhost:8000. i have an registration form in my Home app(localhost:8000) when i submitting the form i am getting.. Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - null does not match any trusted origins. how can i solve this? here is my hosts.py file from django_hosts import patterns, host host_patterns = patterns('', host(r'^(?:www\.)?$', 'Home.urls', name='perfectpesha'), host(r'jobseeker', 'jobseeker.urls', name='jobseeker'), host(r'recruiter', 'recruiter.urls', name='recruiter'), ) here is my registration form {% extends "layout.html" %} {% load i18n %} {% load hosts %} {% load static %} {% load tz %} {% block content %} <form class="form-horizontal" method="POST" action="{% host_url "jobseekerRegister" host "jobseeker" %}"> {% csrf_token %} <div class="formrow"> <input type="text" name="name" class="form-control" required="required" placeholder="Full Name" {% if form.name.errors %}style="border: 1px solid #FE0004"{% endif %}> {% if form.name.errors %} {% for error in form.name.errors %} <span class="help-block-error"> <strong>{{ error }}</strong></span> {% endfor %} {% endif %} </div> <div class="formrow"> <input type="email" name="email" class="form-control" required="required" placeholder="Email" {% if form.email.errors %}style="border: 1px solid #FE0004"{% endif %}> {% if form.email.errors %} … -
Passing Context Processors as parameters in decorator call in django
Is there a way that I can access a context processor value and pass it as parameters to a decorator. Or can I pass request object as parameter to this decorator call. For example like this: @method_decorator(csp_replace(FRAME_ANCESTORS=[context_processor]),name="dispatch") -
Can't connect to Django Websocket
I'm in the process of creating a django websocket and trying to test the simplest version of it with postman ExpState is the name of my app ExpState/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"ws/expstate/", consumers.ExpState.as_asgi()), ] ExpState/consumers.py import json from channels.generic.websocket import WebsocketConsumer class ExpState(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] self.send(text_data=json.dumps({"message": message})) My_Project/asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") # Initialize Django ASGI application early to ensure the AppRegistry # is populated before importing code that may import ORM models. django_asgi_app = get_asgi_application() import chat.routing application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(chat.routing.websocket_urlpatterns)) ), } ) I'm trying to connect to the websocket with postman on ws://127.0.0.1:8000/ws/expstate/ the error postman is giving me is Error: Unexpected server response: 200 -
Using Graphql with Django : Reverse Foreign key relationship using related name for all objects
I'm working with graphene-django ,graphql and django and i want to use the reverse foreign key concept of drf using related name but currently i facing difficulty in achieving that i have put up the models, code and also the output screenshot below import asyncio asyncio.set_event_loop(asyncio.new_event_loop()) import graphene from graphene_django import DjangoObjectType from .models import Category, Book, Grocery, FileUpload from django.db.models import Q from graphene_file_upload.scalars import Upload import decimal class BookType(DjangoObjectType): class Meta: model = Book fields = ( 'id', 'title', 'author', 'isbn', 'pages', 'price', 'quantity', 'description', 'status', 'date_created', ) class FileUploadType(DjangoObjectType): class Meta: model = FileUpload fields = ('id', 'file') class GroceryType(DjangoObjectType): class Meta: model = Grocery # fields = ( # 'product_tag', # 'name', # 'category', # 'price', # 'quantity', # 'imageurl', # 'status', # 'date_created', # ) class CategoryType(DjangoObjectType): grocery = graphene.List(GroceryType) class Meta: model = Category fields = ('id', 'title', 'grocery') class Query(graphene.ObjectType): books = graphene.List( BookType, search=graphene.String(), first=graphene.Int(), skip=graphene.Int(), ) categories = graphene.List(CategoryType) # books = graphene.List(BookType) groceries = graphene.List(GroceryType) files = graphene.List(FileUploadType) # def resolve_books(root, info, **kwargs): # # Querying a list # return Book.objects.all() def resolve_books(self, info, search=None, first=None, skip=None, **kwargs): qs = Book.objects.all() if search: filter = ( Q(id=search) | Q(title__icontains=search) ) …