Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django does not save the form (nothing happens)
\\models.py class BasicSettings(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) settings_description = models.BooleanField(default=False) settings_photo = models.BooleanField(default=False) settings_username = models.BooleanField(default=False) settings_background = models.BooleanField(default=False) \\views.py try: basic_settings = request.user.basicsettings except BasicSettings.DoesNotExist: basic_settings = BasicSettings(user=request.user) if request.method == 'POST': basicsettings_form = BasicSettingsForm( request.POST, instance=basic_settings) else: basicsettings_form = BasicSettingsForm(instance=basic_settings) return render(request, 'dashboard.html', {'basicsettings_form': basicsettings_form}) \\forms.py class BasicSettingsForm(forms.ModelForm): class Meta: model = BasicSettings fields = ( 'settings_description', 'settings_photo', 'settings_username', 'settings_background', ) widgets = { 'settings_description': forms.TextInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'test1'}), 'settings_photo': forms.TextInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'test2'}), 'settings_username': forms.TextInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'test3'}), 'settings_background': forms.TextInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'test4'}), } \.html <form method="POST"> {% csrf_token %} {{ basicsettings_form }} <button type="submit">Dad9adbaiduaadtest</button> When I click on the submit button, the page just refreshes but nothing happens. What might be the reason for this? The code above is just a snippet. Maybe nothing happens because I have multiple forms in one view? The whole view looks like this https://pastebin.com/Bu5NLTX1 but I just wanted to give you the relevant part -
Showing derived value in ModelForm's generated HTML Django
I want to display a ModelForm field with a derived value (from a JS script) in its "row", something like this: /budgetsheet/ Expenses Value Percentage foo 30 0.3 Where the value in bold is the one derived. Here's how I imagined it in HTML: budgetsheet.html ... <head> ... <script> function get_val() { ... document.getElementById("derived_val").value = val } </script> </head> <body> ... <form> <p> {{ expenses }}</p> <p id="derived_val">&nbsp</p> <p>{{ percentage }}</p> ... </form> <body> Where the value in bold is the derived value not in the model fields: models.py class BudgetSheet(models.Model): ... foo = models.FloatField(...) def get_val(self): ... return val While typing this I figured the easy way out is to just add the derived value as a field in the model itself, but it'll still be a problem in terms of restricting it to be not editable (doesn't use input field or is in greyed out input field). It will also add a repetitive field in the model, too. Just wanted to see if there are other solutions to this that are better, or if this solution can get over these problems, and others that may come. Thanks! -
Pylance & Docker - Import "somepackage" could not be resolved
How to deal with this issue when the packages are all inside Docker? For now I have to install the packages locally to enable the intellisense. P.S. The packages DO WORK without installation on local machine. Just wonder how to enable the intellisense like file locating and autocomplete. I feel like I am working on Notepad++ instead of VS Code without intellisense. -
Requests and requests_toolbelt not uploading file to django
I'm trying to upload a file to a django app, to keep track of the upload progress i'm using requests_toolbelt, the http response gives me 200, but the file is not being uploaded. What am i doing wrong? upload_url = 'http://127.0.0.1:8000/upload' client = requests.session() client.get(login_url) csrftoken = client.cookies['csrftoken'] login_data = {'username': username, 'password': password, 'csrfmiddlewaretoken': csrftoken} response = client.post(login_url, data=login_data) client.get(upload_url) csrftoken = client.cookies['csrftoken'] data = encoder.MultipartEncoder(fields={'file': open(file, 'rb'), 'csrfmiddlewaretoken': csrftoken}) monitor = encoder.MultipartEncoderMonitor(data, callback) response = client.post(upload_url, data=monitor, headers={'Content-Type': monitor.content_type}) -
are there two concepts of groups in CentOS
I am currently trying to deal with the permission issues with the /var/www folder for my django Project. Before I could do anything I had to make a user group and put www-data into the user for permission issues. But aparently sudo groupadd webusers command adds a group in the amazon centOs based instance, and when i try to use the command again, it says groupadd: group 'webusers' already exists However when I try to add the user, $ sudo usermod -aG webuser www-data usermod: group 'webuser' does not exist This happens, I am confused hehe... help -
Django ModelForm non-required CharField giving errors
I have a ModelForm for a model that has a couple of files and with every file, a type description (what kind of file it is). This description field on the model has CHOICES. I have set these file uploads and description uploads as hidden fields on my form, and not required. Now the file upload is working, but the description is giving field errors, the placeholder in the dropdown is not a valid choice, it says. That's true, but since it is not required, I would like it to just be left out of the validation and I am stuck on how. My codes, shortened them up a bit to keep it concise. models.py class Dog(models.Model): FILE_TYPE_CHOICES = [ ('SB', 'Stamboom'), ('RB', 'Registratiebewijs'), ('SJP', 'SJP-diploma'), ('CDD', 'CDD-diploma'), ('WT', 'Workingtestdiploma'), ('MISC', 'Overig'), ] dog_id = models.UUIDField(unique=True, default=uuid.uuid4) file_1 = models.FileField(upload_to=user_directory_path, blank=True, validators=[extension_validator]) desc_1 = models.CharField(choices=FILE_TYPE_CHOICES, blank=True, max_length=5) forms.py (I excluded all these fields from the model-code above to keep it more clear, but this is to demonstrate that these fields are not required. If I print the required attribute of 'desc_1' in the view, it also says false class DogForm(ModelForm): class Meta: model = Dog fields = ('stamboomnummer', 'stamboomnaam', 'date_of_birth', … -
Check how many users answered keeps returning first value
I am trying to see how many users answered each option however it will give me the result of how many people answered the first option. Result object is where all answered are saved to. Do I need to make a loop in the html? Would this not work as you cant call Result in to html and filter it ? How would I go around doing this. I see the counter is staying to the first value and keeps looping for each option, but I am confused on a fix for this. HTML <!DOCTYPE html> <html> <head> <title>Admin Panel</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } … -
How to create a report showing revenue by product by year in Django?
Starting with this model: class LineItem(models.Model): created = models.DateTimeField(default=timezone.now) price = models.DecimalField(max_digits=8, decimal_places=2) product = models.CharField(max_length=15) From this, I want to create a report like this: Product. | 2020 | 2021 | 2022 ProdA | $10,000.00 | $9,500.00 | $3,200.00 ProdB | $110,000.00 | $98,000.00 | $35,300.00 ProdC | $119,500.00 | $54,000.00 | $25,300.00 To do this, I could use multiple queries to create a sequence of dictionaries, something like this: [ { "product": "ProdA", 2020: 10000.00, 2021: 9500.00, 2022: 3200.00, }, { "product": "ProdB", 2020: 110000.00, 2021: 98000.00, 2022: 35300.00, }, { "product": "ProdC", 2020: 119500.00, 2021: 54000.00, 2022: 25300.00, }, ] But I'm wondering if there's a better way (e.g, with one query). I'd appreciate any ideas. -
creating a custom user model in django using AbstractBaseUser
I am trying to create a custom user model, when i run python manage.py createsuperuser it promote to enter the username, then password, and confirm password, when i hit enter after that i get this error django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.email model.py : class UserManager(BaseUserManager): def _create_user(self, username, password=None, **extra_fields): if not username: raise ValueError("User must have a username") if not username: raise ValueError("User must have a password") user = self.model( username=username ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_admin', False) return self._create_user(username, password, **extra_fields) def create_superuser(self, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_admin', True) return self._create_user(username, password, **extra_fields) class User(AbstractBaseUser): username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) active = models.BooleanField(default=True) admin = models.BooleanField(default=False) staff = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.username the entire errorlog: PS C:\Users\PC\Desktop\nitrofleet> python manage.py createsuperuser Username: lol Password: Password (again): This password is too short. It must contain at least 8 characters. This password is too common. This password is entirely numeric. Bypass password validation and create user anyway? [y/N]: y Traceback (most recent call last): File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return … -
Python & Django Simple Project
I have small app I am building out about books. I have main app titled 'books' and a startapp, 'titleBooks' , I included a templates folder for my .html files with a base.html. The problem I am getting is when I run the files on 'python manage.py runserver' I do not GET a response from the pages/home.html file with django code (for loop) just to print out the books in db. I am not sure why django does not see the code or file. Within pages/home.html file I do {% extend 'base.html' %} which it can read that file but not the home.html file. Any help is greatly appreciated. settings file below: [![enter image description here][1]][1] -
Is there a --max-requests flag for Daphne?
I have this ASGI applicate with Django and Daphne, and I'm using the following command. daphne -b 0.0.0.0 -p $PORT server.asgi:application Is there a way to add --max-requests and --max-requests-jitter to actively prevent memory leaks? Maybe something like: daphne -b 0.0.0.0 -p $PORT --max-requests 1000 --max-requests-jitter 50 server.asgi:application -
Error install requirements.txt Django project Mac M1
I got my Django project via gitlab and put it on my Macbook M1 but when I put myself in the virtual environment and I install the requirements I have a long error message that appears, I don't don't know how to fix this. Could it be because of the apple silicon chip? Here is the error message: Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: /Users/pierro/Documents/permacool/api_permacool/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/f2/r4cvtlb53hb3r3bvpzkmqnyr0000gn/T/pip-install-zdiid0g3/mysqlclient_87a039d3b25c4c3f8c32778ba1e13516/setup.py'"'"'; __file__='"'"'/private/var/folders/f2/r4cvtlb53hb3r3bvpzkmqnyr0000gn/T/pip-install-zdiid0g3/mysqlclient_87a039d3b25c4c3f8c32778ba1e13516/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/f2/r4cvtlb53hb3r3bvpzkmqnyr0000gn/T/pip-record-bh773nfm/install-record.txt --single-version-externally-managed --compile --install-headers /Users/pierro/Documents/permacool/api_permacool/include/site/python3.8/mysqlclient cwd: /private/var/folders/f2/r4cvtlb53hb3r3bvpzkmqnyr0000gn/T/pip-install-zdiid0g3/mysqlclient_87a039d3b25c4c3f8c32778ba1e13516/ Complete output (43 lines): mysql_config --version ['8.0.28'] mysql_config --libs ['-L/opt/homebrew/opt/mysql-client/lib', '-lmysqlclient', '-lz', '-lzstd', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/opt/homebrew/opt/mysql-client/include/mysql'] ext_options: library_dirs: ['/opt/homebrew/opt/mysql-client/lib'] libraries: ['mysqlclient', 'zstd', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/opt/homebrew/opt/mysql-client/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] running install running build running build_py creating build creating build/lib.macosx-10.14-arm64-3.8 creating build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb creating build/lib.macosx-10.14-arm64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py … -
Object showing instead of the value
I am running through an object and finding out how many people have answered however I try to add it into the context, the object is returned. The Value returned: <calendar.TextCalendar object at 0x7f90f2e7e5e0> Do I need to changed so I do the loop in the html or can I stick to doing it in the views? It returns the memory address Im assuming HTML <!DOCTYPE html> <html> <head> <title>Admin Panel</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } #questionTitle { text-align: left; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } .login_btn:focus { box-shadow: none … -
Google meet clone django or nodejs
I have a django rest app and i want to add an app like google meet to it. Currently I am using django rest framework + channels. I would like to know if in terms of performance django rest framework + channels will be enough for me to manage the different user calls or messages. Should I use django rest + nodejs ? what is the best solution for you ? what technology would you have used ? Do you have any advice ? Thank you -
How to Display Other User's Profile on Django
Currently, I am trying to make a page for other users' profiles. The page includes a section for their profile, which contains profile picture, username, email, and bio. And another section for all of the posts the user posted. But I cannot display the profile section properly. This is what I managed to do so far The Profile module: from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.CharField(max_length=225, blank=True, default='') def __str__(self) -> str: return f"{self.user.username}'s Profile" def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: img.thumbnail((300,300)) img.save(self.image.path) The Post module: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) -> str: return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) The view: class UserProfileView(ListView): model = Post template_name = 'blog/user_profile.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') The blog/user_profile.html: {% extends 'blog/base.html' %} {% block title %}{{ view.kwargs.username }}'s … -
IntegrityError null value in column "name" of relation "tag" violates not-null constraint
I have created an API and am currently testing my post request with Postman. However, I keep getting this error. views.py def post(self, request, *args, **kwargs): serializer = TagSerializer(data=request.data) tag_input = Tag.objects.create(name=request.POST.get("name"), language=request.POST.get("language")) if serializer.is_valid(): serializer.save(tag_input) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('id', 'name', 'language') def create(self, validated_data): return Tag.objects.create(**validated_data) def to_representation(self, data): data = super().to_representation(data) return data models.py class Tag(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def create(self, validated_data): tag_data = validated_data.pop('tag') Tag.objects.create(**tag_data) return tag_data def __str__(self): return self.name or '' -
Django migration OperationalError: index [name] already exists
I hope someone can help me. I have three environments as part of my django development lifecycle, dev, uat and live. Django 3.2.6 with python 3.9.6. I'm trying to add a couple of fields to two of my models but I'm getting an error when I try to migrate the live database, the dev and uat database migrations worked fine. Here is the migration code, generated by makemigrations # Generated by Django 3.2.6 on 2022-01-26 21:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0015_activity_next'), ] operations = [ migrations.AddField( model_name='activity', name='delegated', field=models.BooleanField(default=False), ), migrations.AddField( model_name='activity', name='notified', field=models.BooleanField(default=False), ), migrations.AddField( model_name='adviser', name='digest', field=models.BooleanField(default=True, verbose_name='Send digest of assigned activities once per day?'), ), migrations.AddField( model_name='adviser', name='email', field=models.EmailField(default='i.pigney@tpio.co.uk', max_length=254), ), ] Nothing complex, just adding two fields to my Activity Model and another two fields to my Adviser model. I wasn't expecting any problems but... here is the error traceback: $python manage.py migrate ... Running migrations: Applying tasks.0016_auto_20220130_1904...Traceback (most recent call last): File "/home/.../projects/myproject/myprojectenv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/.../projects/myproject/myprojectenv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: index tasks_activity_provider_id_1557b363 already exists The above exception was the direct cause of the following exception: Traceback (most … -
Model form labels translation
I have included form labels in my translation as follows: class GuestEmailForm(forms.ModelForm): class Meta: model = Guest fields = ['email'] labels = { 'email': _('Add your email for updates'), } However, even though they show up in my translation files and I have added translations, they do not show up translated. Is there a special way to handle labels in model forms? -
Is it possible to download an artifact from Artifactory through Django?
I have a question regarding the possibility of downloading an artifact from Artifactory through Django. Is it possible to use a get request using requests like : import requests r = requests.get(http://localhost:8081/artifactory/libs-release-local/ch/qos/logback/logback-classic/0.9.9/logback-classic-0.9.9.jar?skipUpdateStats=true) or is there another way to download the artifact in python? -
Django form errorlist appears even when there is no attempt to submit
My page when requested through GET appears already with error list, which is not a desirable behavior. I want this error appears when user actually attempts to submit a form without a data required. This is my form Python class: class Place_A_Bid_Form(forms.Form): listing = forms.CharField(widget=forms.TextInput(attrs={"type":"hidden"})) bid = forms.IntegerField(widget=forms.NumberInput(attrs={"class":"form-control"}), min_value=1) Form's html: <form action="{% url 'place_a_bid' listing.title %}"> {% csrf_token %} <div class="form-row"> <div class="col"> {{ form }} </div> <div class="col"> <input class="btn btn-primary" type="submit" value="Place a bid"> </div> </div> </form> And view: def details(request, listing): listing_obj = Listing.objects.get(title=listing) form = Place_A_Bid_Form({"listing":listing_obj.title}) categories = Category.objects.all() user = User.objects.get(username=request.user.username) if listing_obj in user.created_listings.all(): return render(request, "auctions/details.html", { "listing": listing_obj, "categories": categories, "creator": True }) elif listing_obj in user.watchlist.all(): return render(request, "auctions/details.html", { "listing": listing_obj, "categories": categories, "in_watchlist": True, "form": form }) else: return render(request, "auctions/details.html", { "listing": listing_obj, "categories": categories, "in_watchlist": False, "form": form }) What am I doing wrong? Thanks in advance. -
Interconnected Schema
I have a Schema for employee database, But there are two tables which are inter connected to each other, How can I create model for that? Please find image here -
Filter Option with class based view django
I need to filter by a topic/category in my posts; but I think it is dificult to do this with class based views. I have: (this works) models.py class Post(models.Model): class Topic(models.TextChoices): DEV = 'DEVELOPMENT', ('Development') LIFE = 'LIFE', ('Life') OTHER = 'OTHER', ('Other') __empty__ = ('-Unknown-') topic = models.CharField(max_length=15, choices=Topic.choices, default=Topic.__empty__) views.py def filter_view(request, topic): posts = Post.objects.filter( topic__contains=topic ).order_by('-pub_date') return render(request, 'blog/posts.html', {'posts': posts}) urls.py urlpatterns = [ path('', IndexView.as_view(), name='blog'), path('posts/', PostsView.as_view(), name='posts'), path('posts/<slug:slug>-<int:id>/', PostDetailView.as_view(), name='post_detail'), path('posts/topic=<topic>/', filter_view, name='topic'), ] templates/posts.html <div class="my-3"> <span class="bg-white rounded-pill px-2 text-muted">Filter by:</span> <a href="{% url 'blog:topic' 'Development' %}" metho="GET" class="px-2 bg-success bg-opacity-10 text-decoration-none text-success px2">Development</a> <a href="{% url 'blog:topic' 'Life' %}" class="px-2 bg-success bg-opacity-10 text-decoration-none text-success px-2">Life</a> <a href="{% url 'blog:topic' 'Other' %}" class="px-2 bg-success bg-opacity-10 text-decoration-none text-success px-2">Other</a> </div> **But I wanna to use a class based view ** views.py lass TopicView(generic.ListView): template_name = 'blog/posts.html' context_object_name = 'posts' def get_queryset(self): topic = self.request.GET.get('topic') return posts = Post.objects.filter( topic__contains=topic ).order_by('-pub_date') urls.py urlpatterns = [ # Other code path('posts/topic=<topic>/', TopicView.as_view(), name='topic'), ] Error: Internal Server Error: /blog/posts/topic=Development/ Traceback (most recent call last): File "D:\projects\Python3\python3.10.1\Django\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\projects\Python3\python3.10.1\Django\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
BeautifulSoup Not Finding Class
I am using BeautifulSoup to pull the first flight price from a Google Flights query. The flight price contains the class GARawf so I am doing soup.select_one('.GARawf'). While this works for some Google queries I am doing, for others, it is returning None even though they contain the class GARawf when I confirm by inspecting the page. Does anyone know why this is the case? I have attached the links for the queries that return None. https://www.google.com/search?q=Toronto+to+Baie-Saint-Paul+Google+Flights https://www.google.com/search?q=Toronto+to+Quebec+City+Google+Flights views.py for result in first_5_results_list: # search headers headers = {'User-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"} # url to search with url = 'https://www.google.com/search' # query params = { 'q': "toronto to " + result + " google flights", 'gl': 'us', 'hl': 'en', } html = requests.get(url, headers=headers, params=params) soup = BeautifulSoup(html.text, "html.parser") # if the page contains a flight price, get the value if soup.select_one('.GARawf') != None: price = soup.select_one('.GARawf').get_text() else: print("Not Available") -
create Model within Model django (User preferences)
I am somewhat new to Django and I am trying to setup a way that allows users of the system to have preferences. I felt that the best way to do this (forgive me if I am wrong) was to have an additional model, (UserPreferences) and have a One-to-One relationship between each User and UserPreferences however I cannot seem to get it to work. Essentially what I want to do is for every User that is created, I want an an associated UserPreferences which holds the preference values (in this case it is boolean values indicating whether or not the user wants that specific attribute public) for that User. Can anyone see where I am going wrong? class UserPreferences(models.Model): username = models.CharField(max_length=50) age = models.BooleanField(default=True) height = models.BooleanField(default=True) class extendedUser(BaseUserManager): # required method for BaseUserManager def create_user(self, username, password, email, city, dob, height, weight, is_staff, is_superuser, is_admin): pref = UserPreferences.objects.create(username=username) email = self.normalize_email(email) user = self.model( username=username, email=email, dob=dob, city=city, height=height, weight=weight, preferences=pref, is_staff=is_staff, is_superuser=is_superuser, is_admin=is_admin, ) user.set_password(password) user.save() return user def create_superuser(self, username, password, email, city, dob, height, weight): return self.create_user(username, password, email, city, dob, height, weight, True, True, True) class User(AbstractUser): username = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=200) … -
Django simple forum project not displaying modles on page
I have been working on a simple forums application for a few weeks now. The main goal of the project is to have sooner written a post and then for the post to be displayed. The project does not utilize user models. For some reason when the user completes the form for their post their post is not displayed. I was wondering if anyone knew why this is happening or if any of y'all have any tips. views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from . import forms # Create your views here. class ForumForm(generic.CreateView): template_name = 'forums_simple/forum.html' form_class = forms.ForumForm success_url = '/' def form_vaild(self, form): self.object = form.save(commit=False) self.object.save() return super().form_vaild(form) urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'forums' urlpatterns = [ path('', views.ForumForm.as_view(), name='forum') ] models.py from django.db import models # Create your models here. class Post(models.Model): message = models.TextField(blank=True, null=False) created_at = models.DateTimeField(auto_now=True) forms.py from django import forms from . import models class ForumForm(forms.ModelForm): class Meta: model = models.Post fields = ('message',) forum.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> {% for message in …