Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model constraint or business logic
I am building my first django project, it will essentially be an assessment form. Each question will be multiple choice. There is no right or wrong answer the questions but instead a grade of what level they are at. So for each question a user can only select one answer out of the possible three options. I have defined the following models from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: verbose_name_plural = 'Categories' class Question(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) capability = models.TextField() weight = models.FloatField(default=1.0) def __str__(self): return self.capability class Grade(models.Model): name = models.CharField(max_length=100) score = models.PositiveIntegerField() def __str__(self): return self.name class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.PROTECT) grade = models.ForeignKey(Grade, on_delete=models.PROTECT) description = models.TextField() def __str__(self): return f'Q{self.question.id} - {self.description}' class Area(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Assessment(models.Model): created = models.DateTimeField(auto_now_add=True) area = models.ForeignKey(Area, on_delete=models.PROTECT) answers = models.ManyToManyField(Answer) def __str__(self): return f'{self.area} - {self.created}' However an assesment will have multiple answers, however it should only be able to contain one answer per question. Can this type of constraint be designed in the model? or it would be part of the business logic. Esentially the user … -
Django Crispy form based on a ForeignKey
I discovered recently django-crispy-forms. I red many threads on stackoverflow (and elsewhere) but couldn't find one that address my issue. For the sake of simplicity, let consider two models as defined thereafter. One model is a foreign key of the other. My goal is to output a crispy form with all the attributes that can be filled by the user. Namely: foo bar attr1 attr2 [models.py] class ModelA(models.Model): attr1 = models.IntegerField() attr2 = models.CharField(max_length=10) class ModelB(models.Model): foo = models.IntegerField() bar = models.CharField(max_length=50) fk = models.ForeignKey(ModelA, on_delete=models.PROTECT) [views.py] class ModelBForm(forms.ModelForm): class Meta: model = ModelB fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.layout = Layout( Fieldset( Field('foo'), Field('bar'), Field('fk') ) I couldn't find a way to achieve it, even though it looks pretty straightforward on paper. Any help? -
How to Make star Rating using django Database
I have a rating for products stored in django models, now I want the rating to show as a star <script> alert('hello') const Select = (size) => { const children = form.children console.log(children[0]) for (let i=0; i < children.length; i++) { if(i <= size) { children[i].classList.add('checked') } else { children[i].classList.remove('checked') } } } Select(ratings); </script> this is the handler for js <form> <button type="submit" class="fa fa-star fa-1x my-btn " id="first"></button> <button type="submit" class="fa fa-star fa-1x my-btn" id="second"></button> <button type="submit" class="fa fa-star fa-1x my-btn" id="third"></button> <button type="submit" class="fa fa-star fa-1x my-btn" id="fourth"></button> <button type="submit" class="fa fa-star fa-1x my-btn" id="fifth"></button> </form> this is the form, Now i dont know if i have to trigger to make the js work or what esle solution do i have -
Is it possible to upload to a filefield from a formset?
Could you please tell me if it is even possible to upload files from a formset record? I have exhausted everything I have found on the internet. In my template, I have: enctype="multipart/form-data" In my view I have: elif request.method == 'POST': formset = PaymentSheetModelFormset(request.POST, request.FILES) When the page is run, it looks like it will upload, but the file is not actually saved to the database. If I open to the single record form, and upload there, it works perfectly. -
Django blocktranslate not working properly
Hello im working on a django admin with multiple languages. i have my locale directory setup and translation, everything is fine but when i use blocktranslate it doesn't work as i want <li class="breadcrumb-item text-info"> {% blocktranslate with name=opts.verbose_name %} Add {{ name }} {% endblocktranslate %} {% trans 'Add' %} </li> This is my code. The 'Add' inside blocktranslate is not working but trans 'Add' works just fine. I don't know what is the deal here but can u guys help me out. Thanks -
i want to create a urlpattern according to users username
i want to load my profile html with user username on urlpattern my views.py def profile(request): return render(request, 'profile.html') my urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from accounts import views as user_views from . import views # Template Urls! app_name = 'accounts' urlpatterns = [ path('Skolar/',views.base, name= 'base'), path('Register/',views.register,name='register'), path('login/', views.my_login_view, name='login'), path('logout/',views.user_logout,name='logout'), path('<username>',views.profile, name='profile'), path('EditProfile/',views.update_profile,name='editprofile'), ] -
How to align and center 3 divs without affecting middle div
i am making a game score card, and i want to align 3 divs in same line but the score always stays in the center of the page regardless how long the name of the teams are. i tried many things but nothing got me results i wanted, if you can help please do, thanks in advance. team alpha (logo) 0-0 (logo) team beta very long team name (logo) 0-0 (logo) another team {% for match in matches %} <div class="match"> <div class="home"> {{match.home_name}} <img src="{{match.home_logo}}"> </div> <div class="score"> {{match.home_score}} : {{match.away_score}} </div> <div class="away"> <img src="{{match.away_logo}}"> {{match.away_name}} </div> </div> {% endfor %} -
Use boto3 to get total price of an ec2 instance using boto3
reservations = client.describe_instances()['Reservations'] I have used describeinstances() to get instance id to get of every instances first.Is there a way to use get_cost_and_usage() to get price of every instance using instance id using this function? -
ModuleNotFoundError: No module named 'ramaelectricstore.wsgi.application'; 'ramaelectricstore.wsgi' is not a package
I am traying to deploy Django app on AWS EC2 instance but after running this command 4-144:~/ramaelectricstore/ramaelectricstore$ gunicorn --bind 0.0.0.0:8000 ramaelectricstore.wsgi.application I am facing this Error please help me ModuleNotFoundError: No module named 'ramaelectricstore.wsgi.application'; 'ramaelectricstore.wsgi' is not a package -
Clicking on submit at billing address form redirects me at login, instead of redirecting me to shipping address form
I am following a tutorial explainig how to build an eCommerce app with django. I have a cart section [s1] where the customer can see the resume of the products he/she has in the cart. Here the customer can click on a "checkout" button that, according to the tutorial, if the customer is logged in: should lead him/her to a shipping address section [s2] where he/she can fill the shipping address form. else: should lead him/her to a guest authentication section [s2-b] where he/she can continue as guest (the customer is requested to submit his/her email address) or login (the customer is requested to submit user and password) and then reaches the shipping address form section [s2]. Then the app should lead the customer to a billing address form [s3] and then to a finalizing section [s4]. My problem is that I can't go past the shipping address section [s3], because as I click on the submit button, the app redirects me to the login form, (this happens even if I am already logged in) where the message "This field is required" appears for both user and password files, and as I type those in and press Submit button, the … -
page not found in django?
i am new to django. this is the error i keep getting when i try to visit node.name page. page not found Request URL: http://127.0.0.1:8000/Category// urls.py Category/<category_id>/ [name='productlisting'] index.html {% load mptt_tags %} <ul class="root"> {% recursetree listing %} <li> <a href="Category/{{ category_id }}/">{{ node.name }}</a> </li> {% endrecursetree %} </ul> thanks in advance. -
How to develop Cart models and Cart Items model in django rest framework
I am trying to create models for backend in django rest framework. Most of the developers I saw used two models namely Cart and Cart Items for creating cart which is as follows: class Cart(models.Model): owner = models.OneToOneField(User, related_name="cart", on_delete=models.CASCADE, null=True, blank=True) number_of_items = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"User: {self.owner}, items in cart {self.number_of_items}" class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() I am confused as to why one has to create two models. What is the actual use for it? And isnt the item should be many to many fields instead of the foreign key because we are supposed to add multiple products on the cart. Also, why is there number_of_items and also quantity at same time? What is the difference?? My proposed model: class Cart(models.Model): owner = models.OneToOneField(User,related_name="cart", on_delete=models.CASCADE, null=True, blank=True) item = models.ManytoManyField(Product,blank =True, null =True) number_of_items = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
discord.py covid module doesn't work AttributeError: Extra: no attribute 'allow'
I am trying to run the bot on a VPS machine, but I get a bug in the console related to the covid module, but on the computer everything worked as it should. Error in console: Traceback (most recent call last): File "/home/dBot/bot.py", line 10, in <module> from covid import Covid File "/usr/local/lib/python3.10/site-packages/covid/__init__.py", line 2, in <module> from covid.john_hopkins import Covid as JohnHopkinsCovid File "/usr/local/lib/python3.10/site-packages/covid/john_hopkins/__init__.py", line 1, in <module> from .covid import Covid File "/usr/local/lib/python3.10/site-packages/covid/john_hopkins/covid.py", line 5, in <module> from covid.john_hopkins.models import CovidModel, CountryModel File "/usr/local/lib/python3.10/site-packages/covid/john_hopkins/models.py", line 5, in <module> from pydantic import BaseModel, Field File "/usr/local/lib/python3.10/site-packages/pydantic/__init__.py", line 2, in <module> from . import dataclasses File "/usr/local/lib/python3.10/site-packages/pydantic/dataclasses.py", line 7, in <module> from .main import create_model, validate_model File "/usr/local/lib/python3.10/site-packages/pydantic/main.py", line 333, in <module> class BaseModel(Representation, metaclass=ModelMetaclass): File "/usr/local/lib/python3.10/site-packages/pydantic/main.py", line 326, in __new__ cls.__signature__ = ClassAttribute('__signature__', generate_model_signature(cls.__init__, fields, config)) File "/usr/local/lib/python3.10/site-packages/pydantic/utils.py", line 229, in generate_model_signature if config.extra is config.extra.allow: File "/usr/local/lib/python3.10/enum.py", line 146, in __get__ raise AttributeError( AttributeError: Extra: no attribute 'allow' -
How to get mypy to recognize login_required decorator?
I have the following Django view: @login_required def view(request: HttpRequest) -> HttpResponse: if not request.user.some_attribute: return redirect("somewhere") return render(request, "template_name") and a custom User model that has an attribute some_attribute. I use mypy to enforce type checking, with this mypy.ini: [mypy] ignore_missing_imports = True plugins = mypy_django_plugin.main [mypy.plugins.django-stubs] django_settings_module = [PROJECT NAME].settings However, mypy errors with the following: Item "AnonymousUser" of "Union[User, AnonymousUser]" has no attribute "some_attribute" which makes sense because an anonymous user wouldn't have that attribute, but I have a login_required decorator, making AnonymousUsers impossible (it would be a User). How do I tell mypy to ignore this, without using # type: ignore? -
Django email not sent, but executed in the console
I have a sender for a password change signal. When I use endopint, it should send an email, but it only does it in the console. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '465' EMAIL_HOST_USER = "*******" EMAIL_HOST_PASSWORD = "******" EMAIL_USE_SSL = True EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = "*******" Console successfully outputs: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: =?utf-8?b?0JTQvtCx0YDQviDQv9C+0LbQsNC70L7QstCw0YLRjCDQvdCwIHNpenpl?= From: ******** To: kabiljanz0301@gmail.com Date: Sat, 13 Feb 2021 16:30:12 -0000 Message-ID: <161323381275.176437.7948111011454591000@kabiljan-Lenovo-IdeaPad-S340-14API> /user/password_reset/?token=d2883b6ae18eb357ac1 ------------------------------------------------------------------------------- what could be the problem? -
Loop through and Merge Querysets
I am sure this one is straight forward but I cannot seem to get my head around it. I have "Users" who can post "Posts" on my site. Each user can follow other users. The idea is to display all the posts posted by the users that current user is following. Example : Foo followed Bar and Baz. I need to retrieve all the posts from Bar and Baz. Bar = Post.objects.filter(user=3) Baz = Post.objects.filter(user=4) totalpost= list(chain(Bar, Baz)) print(totalpost) On this occasion, when both variables userXposts and temp are hardcoded, I can easily retrieve ONE list of QuerySets neeatly by chaining both QuerySets. However, I cannot have those hardcoded. As such, I am attempted to loop through each user posts and add it in a list since my user can follow X amount of users : QuerySet = Profile.objects.filter(follower=1) for x in QuerySet: userXposts = Post.objects.filter(user=x.user.id) temp = userXposts totalpost= list(chain(userXposts, temp)) temp = [] print("Totalpost after union of userpost and temp: ", totalpost) Here, Profile.objects.filter(follower=1) return two sets of QuerySets, one for Baz and one for Bar. The problem that I have so far is that totalpost endup being a "list of list" (I believe) which forces me to … -
Django models custom error message gets override by serializer
so i'm new to django and i am using django rest framework alongside it. i was trying to customize django model validation error message but when i used the DFR ModelSerializer my custom error message was replaced by ModelSerializers default or that's what i think happened. my class is like this class Category(models.Model): name = models.CharField(max_length=200, blank=False, error_messages={ 'blank': "please enter some name" }) and this is my serializer class CategoryInp(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' for validating my input i wrote this class CategoryView(APIView): def post(self, request): cat = CategoryInp(data=request.data) if not cat.is_valid(): print(cat.errors) i expected to my custom error message to be printed but instead this was printed 'name': [ErrorDetail(string='This field may not be blank.', code='blank')] thanks in advance -
Heroku git push Django migration failure for DuplicateTable
Background Migrating a Django app from Digital Ocean to Heroku. I had problems migrating the data, so I used pg_dump to get the schema and the data of each table. Then ran those scripts in heroku. I loaded my website and I can see the new data coming through. Problem Now when I push new code with the Heroku CLI that auto runs the deployment, it fails for this reason: psycopg2.errors.DuplicateTable: relation "django_content_type" already exists The commands I run are git add . git commit -m "some message" git push heroku master" The Procfile has release: python manage.py migrate which runs the commands, which I thought about taking it out but when I have migrations to run in the future this will cause an issue. Any thoughts? -
Django update dropzone images in a form with other form data
I am building a Django web app that has data entry that includes multiple images upon form submission and I am using dropzone. I have managed to do the create part successfully. However, my challenge comes when I want to update the form. From the views.py file, I am able to send all the rest of the form data for update. My problem is how to obtain images using dropzone in the form so that I can display their thumbnails. My view looks like this: @login_required def vehicle_update(request, pk): listing = get_object_or_404(Listing, pk=pk) template_name='listings/update_vehicle.html' if request.method == 'POST': # Update the data else: listing_form = ListingDetails(instance=listing) vehicle_form = VehicleDetails(instance=listing.vehicle, initial = {'make': listing.vehicle.model.make }) image_list = ListingImages.objects.filter(listing=listing) return render(request, template_name, { 'form': listing_form, 'vehicle_form': vehicle_form, }) So, at this point, I am not sure if the way I am sending images in the else: block is correct. Then, secondly, how to receive images for processing using dropzone.js in the template. I have tried search around but most of the solutions available are for php or the file name is known and location. This is what I have tried with the dropzone function but seems not to be working. var mocks … -
hide the hash, algorithm, salt, etc. information in the password field
I have a question about Django Admin. I don't want to show hashes, algorithms, salts, etc. in the password field of the admin panel. In this case, the ReadOnlyPasswordHashWidget in django.contrib.auth.forms I thought that I could change the variable that points to the template in the class. However, no matter what I did, I could not change it. I could not change it in any way, for example, by creating an app and putting it on django.contrib.auth in INSTALL_APP, or by creating an administrator app that aims to inherit from BaseUser and adding ReadOnlyPasswordHashWidget class to their forms, but it didn't work. I also tried overriding the static/templates/auth/widgets/read_only_password_hash.html file to override the template directly, but that didn't work either. The goal is to display only the help text that comes standard. What would be the best way to do this? Is there any other way? Thank you for reading this far. Regards. -
ModuleNotFoundError: No module named 'rest_framework.response'
in windows from rest_framework import serializers is working. but in 'view.py' file from rest_framwork.response import Response is not working. please help! I checked 'setting.py' file , pip list and runserver state. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mood', 'rest_framework', ] $ pip list Package Version --------------------- ------- asgiref 3.3.1 Django 3.1.6 pip 21.0.1 Python-Rest-Framework 0.3.14 pytz 2021.1 setuptools 41.2.0 six 1.15.0 sqlparse 0.4.1 (venv) ModuleNotFoundError: No module named 'rest_framework.response' what should i do...... -
I have 2 views that have identical post methods, what is the best way to remain DRY
I have a real estate website that has 2 views for 2 separate pages. Each page has a form that allows you to edit the transaction details. One of the pages also allows you to do other things that require the post method. So the views basically look like this: class ViewOne(ListView): # ... def post(self, request, *args, **kwargs): # update transaction logic class ViewTwo(ListView): # ... def post(self, request, *args, **kwargs): # update transaction logic # additional post logic What is the best way to add the post logic that updates the transaction to each view without writing duplicate code? -
How exactly should one merge CRUD or Django templates
In my previous question I asked coders that how can I add multiple articles in my news website without creating a new Html file for each article as it would be difficult to manage so many files on IDE and it also looks impractical. As answers I got recommendation to use Django templates and CRUD to solve these things. I also asked that how big websites like theverge and huffpost manage so many articles on their website but I didn't get satisfactory answer to that. So right now I have only made a homepage using HTML and CSS and that page has various cards for news articles with titles that must open an article when clicked upon. These links are obviously non working right now as I have not put anything in the href tag on their respective HTML files because of reasons I mentioned above. Please Guide me step by step on how should I proceed from here. ///Try to give me all instructions Considering me a complete newbie and noob even the smallest ones. You may also recommend me any article or Youtube video if it describes about my problem exactly. I have already surfed the internet enough … -
Trying to upload audio file with model, but getting "Not Found" error (Django)
I have a 'Music' model which allows a user to upload an audio file through the "FileField". The file gets uploaded to my media folder fine, but the player in the profile.html, comes back with 'error' and in the terminal it says "Not Found" followed by the audio files path. I'm still new to django, so I'd appreciate it if someone can point out what I'm doing wrong here. This is the error in the terminal: Not Found: /my-profile/djangoapp1/media/path/to/audio/05_-_Bicycle_Race.mp3 [13/Feb/2021 15:44:44] "GET /my-profile/djangoapp1/media/path/to/audio/05_-_Bicycle_Race.mp3 HTTP/1.1" 404 6743 models.py class Music(models.Model): track = models.FileField(upload_to='path/to/audio') title = models.TextField(max_length=50) artwork = models.ImageField(upload_to='path/to/img', blank=True) artist = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title forms.py class MusicForm(forms.ModelForm): class Meta: model = Music fields = ['track', 'title', 'artwork'] widgets = { 'title': forms.Textarea(attrs={'rows':1, 'cols':1}), } views.py @login_required def music_upload(request): if request.method == "POST": form = MusicForm(request.POST, request.FILES) if form.is_valid(): user = request.user song = form.save(commit=False) song.artist = user song.save() messages.success(request, f'Track Uploaded') return redirect('my_profile') else: form = MusicForm() return render(request, 'feed/music_upload.html', {'form':form}) profile.html <h3>MUSIC</h3> <audio controls> <source src="djangoapp1/media/path/to/audio/05_-_Bicycle_Race.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> -
I want to create search box
i am using a usercreation form to to create a user i also create a extra model name profile to store some extra data about user with the help of signal and what i want is that search result show one specific result with that username link havings its data on it class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True, help_text='Required.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, required=True, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) model for that user who can store extra data about himself and create automatically a profile by signal from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver Create your models here. class Profile(models.Model): user = models.OneToOneField(User ,on_delete=models.CASCADE,) profile_pic = models.ImageField(upload_to='profile_pics',default='default.png',) twitter = models.URLField(max_length=80, blank=True,) facebook = models.URLField(max_length=80, blank=True,) about = models.CharField(max_length=1500, blank=True,) joined_date = models.DateTimeField(default=timezone.now,editable=False) dob = models.DateField(blank=True,null=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, *args, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save()