Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get a list of pending invitations for a user using django-invitations?
I can see in the source code for django-invitations that there is a manager with an all_valid method but I'm having trouble connecting the dots back to request.user. I'm also using django-allauth. -
Django unique_together versus explicit duplicate restriction
I currently have this try-except block to restrict duplication of user and post fields in Follow model: def follow(request, post_pk): user = request.user post = Post.objects.get(id=post_pk) try: _follow = Follow.objects.get(user=user, post=post) except Follow.DoesNotExist: _follow = Follow(user=user, post=post) _follow.save() return redirect(request.META.get("HTTP_REFERER")) I recently just learned about unique_together in class Meta. Now, I can modify the model like this: class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) class Meta: unique_together = (('user', 'post'),) Having done so, is it safe to remove the explicit duplicate restriction in try-block of views.py? The code will then look like this: def follow(request, post_pk): user = request.user post = Post.objects.get(id=post_pk) _follow = Follow(user=user, post=post) _follow.save() return redirect(request.META.get("HTTP_REFERER")) -
I am not able to run `python manage.py runserver` in my vscode terminal but the same command is running in my system terminal
VScode terminal: System terminal: -
Django testing a form, self.request kwargs gives keyerror
I have a modelform that uses __init__ to get kwargs. When running tests, I get a keyerror: 'requests'. For my unit test, I setup an existing user and existing object to test for duplicates per user. Here is the form and test: class CourseForm(ModelForm): """ Form used for both creating a new course or updating an existing course.""" class Meta: model = Course fields = ('course_name', 'grade_level',) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.qc = Course.objects.filter(user=self.request.user) super().__init__(*args, **kwargs) def clean(self): super(CourseForm, self).clean() course_name = self.cleaned_data.get('course_name') grade_level = self.cleaned_data.get('grade_level') # check exising course_name per user # exclude(pk=self.instance.pk) because when we update we don't have to consider the current name if course_name and self.qc.exclude(pk=self.instance.pk).filter(course_name__iexact=course_name).exists(): raise ValidationError("A course with that name already exists.") return self.cleaned_data class CourseFormTests(TestCase): @classmethod def setUp(self): self.user = CustomUser.objects.create_user( username='tester', email='tester@email.com', password='tester123', is_teacher=True, is_active=True, ) self.user.save() self.my_course = Course(user=self.user, id='4d192045-07fa-477f-bac2-5a99fe2e7c04', course_name="name", grade_level="SEC") self.my_course.save() def test_CourseForm_valid(self): form = CourseForm(self.user, data={ 'user': self.user, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7c04', 'course_name': "Science", 'grade_level': "SEC" },) self.assertTrue(form.is_valid()) def test_CourseForm_invalid_name_too_long(self): form = CourseForm(self.user, data={ 'user': self.user, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7c05', 'course_name': "NameistoolongforthistobeOKNameistoolongforthistobeOK", 'grade_level': "SEC" },) self.assertFalse(form.is_valid()) def test_CourseForm_invalid_name_exists(self): form = CourseForm(self.user, data={ 'user': self.user, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7c05', 'course_name': "name", 'grade_level': "SEC" },) self.assertFalse(form.is_valid()) The exact error is: line 107, in … -
Opening the acquired URL in the same tab rather than loading it on a new window
I am a web hobbyist using Selenium with Django for some online web scraping. I have created a web app that iterates through the different dates of birth to find valid credentials to log in, but after logging in, it opens up a new window to show the results. I want the acquired URL (acquired through the driver.get function) to open up on the same tab instead of a new window whenever I successfully log in. from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By def search_student(registration, dob, set_driver): set_driver.get("http://clearance2.giki.edu.pk:8005/ranks/") username = set_driver.find_element(By.NAME, "username") password = set_driver.find_element(By.NAME, "password") username.send_keys(registration) password.send_keys(dob) set_driver.find_element(By.NAME, "bt1").click() return set_driver op = webdriver.ChromeOptions() op.add_argument('headless') driver = webdriver.Chrome(ChromeDriverManager().install(), options=op) reg_no = input("Enter reg_no: ") birth_year = int(reg_no[0:4]) - 19 date = (birth_year * 10000) + 101 found = False print("Searching...") count = 1 while (count < 6) and (not found): date = (birth_year * 10000) + 101 for i in range(0, 383): driver = search_student(reg_no, date, driver) if driver.current_url == "http://clearance2.giki.edu.pk:8005/ranks/ranks.php": print(f"successfully logged in with DOB {date}") found = True driver.quit() break date += 1 if date % 100 == 32: date -= 32 date += 100 birth_year += pow(-1, count + 1) * … -
Django always accesses default database when creating users
I have django project with multiple databases: DATABASES = { 'default': {}, 'db1': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / DB1_NAME, }, 'db2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / DB2_NAME, } } DATABASE_ROUTERS = ['app.router1.Router1', 'app.router2.Router2'] The router for db1 is defined: class Router1: route_app_labels = {'app', 'sessions', 'auth', 'admin', 'contenttypes'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'db1' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'db1' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'db1' return None Everything seems to work well, except creating new users. When I try to create a new user, I get the following error: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. When I change db1 to default, user creation seems works well. -
User instance automatically created after manage.py migrate
Upon defining a custom User model, I created a migration prior to executing python manage.py migrate. Upon checking the table, a single instance of User is created: <User: AnonymousUser>. Why would this instance even exist in the first place? I have no knowledge of any CREATE operations taking place. (venv) λ python manage.py makemigrations authors --name "created_user_model" Migrations for 'authors': authors\migrations\0001_created_user_model.py - Create model User - Create model Profile (venv) λ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, authors, contenttypes, guardian, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying authors.0001_created_user_model... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying guardian.0001_initial... OK Applying guardian.0002_generic_permissions_index... OK Applying sessions.0001_initial... OK (venv) λ python manage.py shell Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib.auth import get_user_model >>> get_user_model().objects.all() <QuerySet [<User: AnonymousUser>]> settings.py AUTH_USER_MODEL = "authors.User" from django.contrib.auth.models import AbstractUser from django.conf … -
View only works with permissions.AllowAny and authentication_classes = []
So im new to Django and DRF so Im probably doing something very noobish here. Im making a react app served from Django and using Django Rest Framework to create the API to manage the database. I have the API set up with session authentication. Mostly it works fine, I can log in and out, register user. I can make post requests except this one view that I use to create an object and add it to the PostgreSQL database. The code sample just below this paragraph is the only way I can get it to work, which is not ideal. If anyone could even just point me in a general direction even if you don't know exactly what is happening that would be amazing because I am completely lost here. Thanks class StationCreate(generics.CreateAPIView): authentication_classes = [] permission_classes = (permissions.AllowAny,) queryset = Station.objects.all(), serializer_class = StationSerializer This works like this because there is no authentication and AllowAny permissions. Thats no good of course so I try to add: permission_classes = [DjangoModelPermissions,] and remove: authentication_classes = [] I then went to the admin panel and made sure that my user was set to use all user permissions but when I run … -
Django Rest Framework, help describing a model containing ManyToMany relationship with users and extending user information
I have a model that basically works like an event. An event is create by a user (ForeignKey). Then other users can join the event and bring guests (Not users but just "anon" users). Meaning that when users join an event they can state how many outside guests they want to bring. I am having trouble figuring out how to extend the model to include the number of guests each user would like to bring. A user can join multiple events and bring a different amount of guests to each event. Another thing is that when a user creates an event, they supply a list of diet options. These options are the available diets, thus when another User joins the event they have to select which diet they are. The potential guests attached to the users joining are simply a number and thus it is not needed to choose the diet of all the guests a user wants to add. Now finally, my current model looks like this, class VeganParticipants(models.Model): participant = models.ForeignKey(MyUser, related_name='vegan_participant', on_delete=models.CASCADE) guests = models.PositiveIntegerField(default=0) class VegetarianParticipants(models.Model): participant = models.ForeignKey(MyUser, related_name='vegetarian_participant', on_delete=models.CASCADE) guests = models.PositiveIntegerField(default=0) class MeatParticipants(models.Model): participant = models.ForeignKey(MyUser, related_name='meat_participant', on_delete=models.CASCADE) guests = models.PositiveIntegerField(default=0) class Madklub(models.Model): … -
SeleniumBase Django Integration
I recently stumbled across a way to make selenium faster using SeleniumBase. I am working on a website that has to parse a google shopping page. It uses selenium to wake the page up because there is javascript on the page and it uses BeautifulSoup to parse the page contents... and it's slow. I have been trying for a few days now to integrate Django and SeleniumBase with no luck. The Django views combined with the class structure of selenium base is stretching my knowledge of raw python. I have a function at the bottom of my code that parses the page content that includes SeleniumBase and BeautifulSoup and a call of the function and forloop at the top to loop through the contents. I have gotten several error messages and I still think I am far away from the solution so I don't feel there is a need to post them here because none seemed too significant. Any help is greatly appreciated. P.S. I am slightly new to django and python and really new to Selenium and SeleniumBase def home(request): form = SearchForm(request.POST or None) if form.is_valid(): form.save() if request.POST: for google_post in google_initiate(request, self): #Do some stuff #Make … -
How to retrieve the method of a Django model by specifying parameters in the URL with REST framework?
I have a model Account with a ForeignKey user and a method total_value() that returns a float64. I would like to GET the float value by entering the account and user primary keys as parameters in the URL. To do that I catch parameters with request.query_params and select the desired Account object but the framework throws an error. What amI missing ? https://mysite/api/widget/total/?account=1&owner=1 'Account' object is not iterable Please find my code below. models.py class Account(TimestampedModel): name = models.CharField(max_length=20, null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def total_value(self): return do_stuff(self) serializer.py class TotalAssetsValueSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('total_value',) view.py class TotalAssetsValueView(viewsets.ModelViewSet): serializer_class = TotalAssetsValueSerializer http_method_names = ['get'] def get_queryset(self): user = self.request.query_params.get('user') account = self.request.query_params.get('account') return Account.objects.get(pk=account, user=user) I'm sure there an account with pk=1 and user=1, so maybe my mistake is that I return an object not a queryset. Unfortunnatly when I filter instead of get it return []. -
django.core.exceptions.ImproperlyConfigured: Set the DB_USER environment variable
This project was working good until I reinstalled django-environ to make DB_USER, exc After I tried to execute and I had this error ... settings.py from pathlib import Path import os import environ env = environ.Env( #Set casting, default value DEBUG=(bool, False) ) READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False) """if READ_DOT_ENV_FILE: environ.Env.read_env()""" #reading .env file #environ.Env.read_env() #False if not in os.environ DEBUG = env('DEBUG') # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') DATABASES FROM settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("DB_NAME"), 'USER': env("DB_USER"), 'PASSWORD': env("DB_PASSWORD"), 'HOST': env("DB_HOST"), 'PORT': env("DB_PORT"), } } .env file it is located at the same directory like settings.py DEBUG=False SECRET_KEY='KEY' DB_NAME=DB DB_USER=USER DB_PASSWORD=PASSWORD DB_HOST=HOST DB_PORT= And error File "D:\CRM\web\settings.py", line 96, in <module> 'USER': env("DB_USER"), File "D:\CRM\env\lib\site-packages\environ\environ.py", line 197, in __call__ return self.get_value( File "D:\CRM\env\lib\site-packages\environ\environ.py", line 407, in get_value raise ImproperlyConfigured(error_msg) from exc django.core.exceptions.ImproperlyConfigured: Set the DB_USER environment variable (env) -
AssertionError encrypt in django
so i want to encrypt text to audio mp3. but when i run the code, there's error message Exception Type: AssertionError. and it's say there's error at assert len(key) == key_bytes can someone please check what's error with the function? i want encrypt using AES 128 and 256, please help me. from Crypto.Cipher import AES from Crypto.Util import Counter from Crypto import Random import binascii key_bytes = 16 # Takes as input a 32-byte key and an arbitrary-length plaintext and returns a # pair (iv, ciphtertext). "iv" stands for initialization vector. def encrypt(key, testaudio): assert len(key) == key_bytes print(testaudio) print(key) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key, AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(testaudio) print(iv) print(ciphertext) return (iv, ciphertext) -
django authentication model - login with emailed link?
Is there a way to set up the django authentication model where, instead of a password, users put in their email address, and then are emailed a link that they click on to login with? If so, are there any tutorials on how to set this up? -
Import "phonenumber_field.modelfields" could not be resolved
I have django project and I try to add phonenumber package, I've done 'pip install django-phonenumber-field[phonenumbers]' and I imported the library to my .models but it shows up as an error but it works anyways, the error is called: "Import "phonenumber_field.modelfields" could not be resolved(reportMissingImports)" how do I fix the problem so it won't tell me its a problem and will work like everything else? Please help :3 my code and error -
MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled - DJANGO + REACTJS
I have a django + reactjs application that I have deployed in digitalocean app platform. I am using the production build, made with command npm rub build, of reactjs and serving it with the django. I am using digitalocean spaces for static and media files sotrage and serving. Now after deployment I am getting the following errors in the console: Refused to apply style from 'https://solvelitigation.com/static/css/main.e8b3c255.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Refused to apply style from 'https://solvelitigation.com/static/css/main.e8b3c255.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. efused to execute script from 'https://solvelitigation.com/static/js/main.a796034b.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Manifest: Line: 1, column: 1, Syntax error. Refused to apply style from 'https://solvelitigation.com/static/css/main.e8b3c255.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Because of the above errors nothing is being rendered in the page. I have no idea why this is happeing and how to solve them. Please suggest to me how to solve this.I have tried a number of solutions from … -
Git deleted my files while pull. How to restore the files?
Git deleted my files while pull. the deleted files were not committed. How do I restore that files back into my working directory? I have attached a screenshot for your reference. screenshot here -
Comment resolver ce bug?
NoneType' object has no attribute 'utcoffset Request Method: GET Request URL: http://127.0.0.1:8000/admin/events/evenement/add/ Django Version: 4.1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'utcoffset' Exception Location: C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\timezone.py, line 256, in is_aware Raised during: django.contrib.admin.options.add_view Python Executable: C:\Users\lenovo\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.5 Python Path: ['C:\web', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf'] Server time: Sun, 21 Aug 2022 17:51:06 +0000 -
Django pass variable to Python script
I have a Django app, with 2 pages: index.html and device_list.html Index page: <div class="search"> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="text" class="input" name="UserInput"> </form> </div> <div class="btn"> <button class="btns" onclick="location.href='{% url 'script' %}'">Generate</button> </div> </div> here is device_list.html page: {% extends "base.html" %} {% block content %} {{output}} {% endblock content %} Views.py: def index(request): return render(request, 'index.html') def device_list(request): if request.method == 'POST': form = SiteCodeForm(request.POST) if form.is_valid(): command = ["python","run.py","VARIABLE" ] process = Popen(command, stdout=PIPE, stderr=STDOUT) output = process.stdout.read() print(output) ----- IM STUCK HERE ----- So I don't know how to proceed, and pass the variable from index page to the python script that I have in views. It actually runs the script, and I can see the result in the terminal, but the output won't show up in the device_list.html - it's empty. -
Django : NoReverseMatch
Im having issues with indexing inside reference point in url. I have quite complicated nested object of two raw quries and string inside tuple inside list. Point is that referencing sometimes works and sometimes does not and I don't really get why. This piece of html works really well. <td><a href="{% url 'company_info' pair.0.0.0.ticker %}">{{pair.0.0.0.ticker}}</a></td> But this one fails <td><a href="{% url 'company_info' pair.1.0.0.ticker %}">{{pair.1.0.0.ticker}}</a></td> What's more django properly renders this : <td>{{pair.1.0.0.ticker}}</td> But has problem with this one : <a href="{% url 'company_info' pair.1.0.0.ticker %}"> Which really indexes the same object. So in one place its ok and in another it fails. What might be causing that? Sorry if its a little bit messy explanation but html its not really my thing and I might lack some vocabulary. Best! -
Initialize django ModelForm user field with current logged user
I'm trying to initialize some fields of my NewArticleForm with static data. In particular, I want to set the author field with the current logged user/author, and shouldn't be modifyable. This page is reachable only from logged user, and the information is also stored in the url: path('<int:user_id>/create', views.add_article, name='insert'), forms.py: class NewArticleForm(forms.ModelForm): class Meta: model = Article fields = ['author','title', 'content', 'pub_date'] pub_date = forms.DateTimeField(initial=timezone.now()) def save(self, commit=True): article = super(NewArticleForm, self).save(commit=False) if commit: article.save() return article models.py: from django.db import models from django.contrib.auth.models import User class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField() title = models.CharField(max_length=50) content = models.TextField() def __str__(self): return self.title def get_year(self): return self.pub_date.year def get_month(self): return self.pub_date.month views.py: @login_required def add_article(request, user_id): if request.method == 'POST': form = NewArticleForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Articolo inserito con successo!') return redirect('/blog_app/') else: messages.warning(request, 'Qualche campo non è corretto, operazione fallita.') form = NewArticleForm() return render(request, template_name='blog_app/insert.html', context={'insert_form':form}) How can I set author with the current logged user? Bonus question: Why pub_date field, which is a DateTimeField, is displayed as text type? I can't change it. -
Default tabular inline to a, b ,c & d
I want to default my tabular inline form to A B C D class AnswerInline(admin.TabularInline): model = Answer extra=4 -
IntelliJ IDEA not loading dependencies from docker compose - python django
I have set up a remote interpreter from the docker-compose option for a Django project. Still, it is showing me red squiggly lines under the package imports. How can I fix this? docker-compose.yml services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:14.5-alpine3.16 volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme volumes: dev-db-data: Code ss Docker ss Docker config ss -
Calling same celery task multiple times in Django
I am totally new to celery and trying to call the same celery task multiple times parallel. Basically, my task creates some data in an external third-party app through API and export created data with a third-party generated id. Now if I run the same tasks multiple times, third-party generated id changes to the latest instance of the task. Can I know how can I solve this issue? I tried saving the third-party generated id with task id in the results backend, but then how to do I, access this data form results backend? Is there any other way to do it? -
Django - button redirecting to {% url 'index' %}
I can't find any solution on any article so I'm asking here. I'd like to make button which is gonna redirect user to specific url. I have already did it this way: <button onclick="location.href='create_recipe/'" type="button" >Create new Recipe</button> but instead of passing whole link I'd like to use {% url 'some_view' %} but I do not have an idea how I should do that. Is it even possible to do that ? It has to be <button>, edit: something like: <button type="button" class="btn btn-outline-secondary"><a href="{% url 'index' %}">Create new Recipe</a></button> also does not work