Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limit the amount of user registration in django
I am newbie in django a I have a question. My system, developed in django, needs to register only the amount of user given in a registration page. How I do to verificate and to limit the amount of registered user? Follow my view: from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.utils.decorators import method_decorator from apps.criarusuario.forms import SignUpForm from apps.cadastro.models import CadastroCliente # table with amount of users to be registered @login_required def signup(request): form = SignUpForm(request.POST) count = CadastroCliente.qtde_usuarios #count the size of registered user if request.method == 'POST': if form.is_valid(): if (CadastroCliente.qtde_usuarios == count): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) else: if (CadastroCliente.qtde_usuarios == count): form = SignUpForm() return render(request, 'criarusuario/signup.html', {'form': form}) Thank you very much! -
How to keep duplicate query set in django
Hello i am new to django and i am stuck in one small problem def doctor_view_appointment(request): apptdoctor=models.Appointment.objects.all().filter(doctorId=request.user.id,status=True) pat_identity=[] for a in apptdoctor: pat_identity.append(a.patientId) print(pat_identity) pat_data=models.Patient.objects.all().filter(status=True,user_id__in=pat_identity) print(pat_data) appt_doctor=zip(apptdoctor,pat_data) data={ 'appt_doctor': appt_doctor, } return render(request,'doctor_view_appointment.html',context=data) In this code the print result of pat_identity is [5, 20, 5] (they are appointmetn id) and the result of pat_data is <QuerySet [<Patient: User1>, <Patient: User2>]> but i need the result <QuerySet [<Patient: User1>, <Patient: User2>,<Patient: User1>]> what should i do for this output -
Django adding sub headings to a form (Failed lookup for key)
I have a model form with lots of options(I removed most of them for this). I would like to add sub headings to make it look better and so its more readable. From my research I couldn't find a definitive way to do it but the few posts I found said to use crispy forms with a helper and multiple field sets. forms.py from crispy_forms.helper import FormHelper class PostForm(ModelForm): class Meta: model = Post fields = 'title', 'manufacture', 'model', 'aspiration', 'image', 'content', def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Models.objects.none() self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'MY SubHeading ONE' 'title' 'manufacture' ), Fieldset( 'MY SubHeading TWO' 'model' 'aspiration' 'image' 'content' ) ) if 'manufacture' in self.data: try: model_manufacture_id = int(self.data.get('manufacture')) self.fields['model'].queryset = Models.objects.filter(model_manufacture_id=model_manufacture_id)#.order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['model'].queryset = self.instance.country.city_set#.order_by('name') The if 'manufacture' is for a custom dropdown and is not related along with self.fields['model'].queryset = Models.objects.none() post_form.html <div class="content-section"> <form method="post" enctype="multipart/form-data" id="PostForm" data-models-url="{% url 'ajax' %}" novalidate> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {% crispy PostForm PostForm.FormHelper %} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> … -
Receive email from the another sender not myself
I use my Gmail account to receive an e-mail when a visitor submits the contact form on my website. This is how I have set the parameters in my views.py: email_from = f'{sender_name} <{sender_email>' email_to = ['myemailaddress@gmail.com', ] send_mail(email_subject, '', email_from, email_to, html_message=html_message) And I receive the email and everything is fine — except that the email is coming from myself (the from is myself) not the name and email address of the person submitted the form as I've set in email_from field. How to fix this? -
How to escape the ? character in django using path
I have a title section for one of my models, and in there, when I add a ? in it, and redirect the page with that URL, it adds an extra / in the URL, and leads me to a 404 Not Found. So my question is: How can I escape this character without having to replace it. Also, the extra requirement is, how can I do this with path()? In the urls.py. I am not using regex for this. Please let me know. Thanks! -
Post default to form django
I have a car rental project, in each DetailView of a car, there is form that allows the user to book the car. My problem is i want to send the car model and brand of the car from where the reservation form was used. Here is my code : models.py : class Car(models.Model): trans = (('Manual','Manual'),('Automatic','Automatic')) Fuel = (('Essence','Essence'),('Diesel','Diesel')) brand = models.CharField(max_length=100, blank=False, null=False) model = models.CharField(max_length=100, blank=False, null=False) Transmission = models.CharField(max_length=100, blank=False, null=False, choices=trans, default='Manual') Seats = models.IntegerField(blank=False, null=False, default= 2) fuel = models.CharField(max_length=100, blank=False, null=False, choices=Fuel, default='Essence') features = models.ManyToManyField('Features',blank=False, null=False, related_name='cars') featured = models.BooleanField(default=False) price = models.IntegerField(blank=False, null=False, default= 0) image = models.ImageField(upload_to="media/carimages/", default=None,blank=True,) thumbnail_image = models.ImageField(upload_to="media/thumbnailcarimages/", default=None, blank=True, null=True) def __str__(self): return self.brand + ' ' + self.model class Reservationform(models.Model): pickup = models.CharField(max_length=50, blank=False) pickup_date = models.CharField(max_length=50, blank=False) pickup_time = models.CharField(max_length=50, blank=False) phone = models.CharField(max_length=50, blank=False) treated = models.BooleanField(default=False) b = models.ForeignKey(Car,on_delete=models.CASCADE, default=Car.brand) m = models.ForeignKey(Car,on_delete=models.CASCADE, default=Car.model) forms.py class ReservationForm(forms.ModelForm): class Meta: model = Reservationform fields = ('pickup','pickup_date','pickup_time','b','m','phone',) widgets ={'pickup': forms.TextInput(attrs={'class': "form-control", 'placeholder': "Aéroport Tunis Carthge"}), 'pickup_date': forms.TextInput(attrs={'class': "form-control","id":"book_pick_date" }), 'pickup_time': forms.TextInput(attrs={'class': "form-control", "id":"time_pick"}), 'b': forms.TextInput(), 'm': forms.TextInput(), 'phone': forms.TextInput(attrs={'class': "form-control", "placeholder": "Your contact number"}), } Views.py : class SingleCar(generic.DetailView, FormMixin): model = Car context_object_name … -
Permission denied error while trying to save image inside Django views
I'm trying to save an image that I'm scraping from IMDB(using bs4) but I'm getting this error: [Errno 13] Permission denied: '/media/Django-Unchained.webp' My code was working fine and I could save the images inside the media directory until I changed some other parts of my code which are completely unrelatable to saving image objects or permissions. When I restarted the server I suddenly faced this error. Why would such a thing happen? Thanks in advance for your ideas on solving this. -
Django urls relation
Whenever I add any '/' in front of the action parameter or after the action parameter then a '?' is always included in the URL. What is the relation between '/' and '?'.It doesn't happen with an anchor tag. <form action="about"> <button type="submit"> hello world </button> -
how to remove html encodings from a string in django
I have used the strip_tags function. It removes tags like "<p>, <b>", etc but things like "&nbsp; &ldquo;" and other html encodings remain. How to remove them ? -
Error getting ManyToMany field from an object
How to execute some functionality, after creating an object in the admin area? I'm trying to use post_save signal and trying to get all objects from my field, which has type ManyToMany, I also use sorting package (sortedm2m). When I save the object I try to output this field, but when I create I get an empty queryset, and when I edit I get the old queryset, without the current changes. class Servers(models.Model): name = models.CharField(max_length=120, default="name") content = SortedManyToManyField(Content) @receiver(post_save, sender=Servers) def create_server(sender, instance, **kwargs): print(instance.content.all()) -
While building a DRF package, unable to import dependencies from Django packages
I am writing a package for reusable APIs and want to later publish it on PyPI. I have already published a basic python package which has a helloworld() to understand how this would work. I have a set of APIs in my DRF app. I moved that app in a my packaging directory of setup.py. Also, I have added external dependencies to the setup.py. setup( name="django_restframework", version="0.0.1", description="Some description", long_description=get_doc(), long_description_content_type="text/markdown", url="https://github.com/some/path.git", py_modules=['manager', 'serizalizer', 'models', 'services', 'tests', 'urls', 'views'], package_dir={'': 'django_restframework_2fa'}, author='Jeet Patel', author_email='********@gmail.com', python_requires='>=3.7', include_package_data=True, zip_safe=False, packages=find_packages( exclude=['tests', 'tests.*', 'licenses', 'requirements']), classifiers=[ "Environment :: Web Environment", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Framework :: Django", "Framework :: Django :: 3.1", "Framework :: Django :: 3.2", 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP', ], install_requires=[ "djangorestframework", "django", "djangorestframework-simplejwt", "pyjwt", "twilio==6.55.0", "djangorestframework-simplejwt==4.6.0", "django-phonenumber-field==5.2.0", "phonenumbers==8.12.24", ], extra_requires={ "dev": [ "pytest>=3.7", "twine 3.4.1", ] } ) Now, I created settings.py in the the app directory and it has this - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'phonenumber_field', 'rest_framework', 'django_restframework_2fa', … -
Why is this django views code not working?
hi I'm having trouble with the image Field in Django forms module, I'm trying to create a form in a website where the users are able to upload images to the database and I'm using Django built in form module to create a form page in the HTML page and once the user upload their data which include some images they would press submit and this should upload it in the backend but for some reason I'm not getting anything can anyone help??? Here is my code: def CreateQueries(request): queryform = QueryForm() if request.method == 'POST': queryform = QueryForm(request.POST, request.FILES) if queryform.is_valid(): title_question = queryform.cleaned_data.get('title') first_question = queryform.cleaned_data.get('Query1') second_question = queryform.cleaned_data.get('Query2') first_image = queryform.cleaned_data.get('Image1') second_image = queryform.cleaned_data.get('Image2') queries = Queries.objects.create( Topic=title_question, Q1=first_question, Q2=second_question, Qimg1=first_image, Qimg2=second_image ) queries.save() print(queries) return render(request, 'Querie/CreateQueries.html', {'form': queryform}) -
Django - Dynamically generating pdf files, storing them, and allowing users to download them in a .zip archive
I made a django app which allows users to complete multiple-choice question tests and saves the given answers to the database. What I would like to do is for the staff to be able to download, for each test created, at the end of it, a zip archive containing a pdf file for each participant, showing their answers to the questions in the test. My first idea was to generate the pdf files and save them to a binary field in a model, but I think creating an actual file would be better and make things smoother for the zip creation too. Problem is, every time I worked with static file management, it was user-uploaded files. I don't know how to dynamically generate and save files inside of a view. This guide explains how to return pdf files as an http response, but what I'm looking for is a way to permanently store them on my server. Is it as easy as just opening a file and saving it or is there anything to be done beyond that? I see django has a File class but I'm still kinda unsure how to go about this and if there are any … -
Create a dataframe from the model
I am writing an application using Django and I ran into a problem. I have models that are as follows: class Feature(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) feature_name = models.CharField(max_length=300) feature_code = models.CharField(max_length=50, unique=True) feature_predictable = models.BooleanField(default=False) def __str__(self): return self.feature_name def breed_name_based_upload_to(instance, filename): return "breeds/{0}/{1}".format(instance.breed_name, filename) class Breed(models.Model): breed_name = models.CharField(max_length=300) breed_features = models.ManyToManyField(Feature) breed_image = models.ImageField(default='no_image.png', upload_to=breed_name_based_upload_to) breed_visible = models.BooleanField(default=True) def __str__(self): return self.breed_name class FeatureValue(models.Model): breed = models.ForeignKey(Breed, on_delete=models.CASCADE) feature = models.ForeignKey(Feature, on_delete=models.CASCADE) feature_value = IntegerRangeField(min_value=1, max_value=3, default=1) class Meta: unique_together = ('breed', 'feature') In the 'Feature' model, I have 3 records with feature_code with values for example 'value1', 'value2', 'value3'. In the 'Breed' model I also have 3 records, with each of these records assigned values for each record from the 'Feature' model (I use the FeatureValue model for assigning values). Now I need to use the Breed model to create a DataFrame that would look like this: id breed_name value1 value2 value3 0 name1 2 1 3 1 name2 1 2 2 2 name3 3 3 3 At the moment, using this code: dataframe = pandas.DataFrame().from_records(list( Breed.objects.all().values( 'id', 'breed_name', 'featurevalue__feature_value' ) )) I managed to achieve something like this: id breed_name featurevalue__feature_value 0 name1 2 0 … -
How to run django admin app without media files on local env?
I dont have media files on local machine, how to disable Error FileNotFoundError? Without simulating folder structure in MEDIA. -
How to see if username already exists in UserCreationField - Django
I am creating a simple registration field in Django for my website. I want to see if a username already exists and display an error if it does. For example, if I had an account with the username of hi, and another user tried to create an account with the username of hi, after they click on the submit button, I want to raise an error. Right now, if I was to create an account with a username that already exists, Django will not create the account but does not display an error. My code is down bellow. Views.py def index(request,*args, **kwargs): return render(request, "index.html", {} ) def register(request, ): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been successfully created, {username} ') return redirect('login') context = {'form': form} return render(request, "register.html", context ) def login(request,): return render(request,"login.html") Forms.py class CreateUserForm(UserCreationForm): username = forms.CharField(required=True, max_length=30, ) email = forms.EmailField(required=True) first_name = forms.CharField(required=True, max_length=50) last_name = forms.CharField(required=True, max_length=50) class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2',] I don't know if you need this but here is my register.html: <!--Might need to inherit from base.html--> … -
save() prohibited to prevent data loss due to unsaved related object 'log'
I am new to django.. I cannot understand what is this error. Can someone help me solve this issue? Traceback (most recent call last): File "C:\Error logger\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Error logger\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Error logger\errorLogger\log\views.py", line 130, in add_solution s.save() File "C:\Error logger\errorLogger\log\models.py", line 41, in save super().save(*args, **kwargs) File "C:\Error logger\venv\lib\site-packages\django\db\models\base.py", line 682, in save self._prepare_related_fields_for_save(operation_name='save') File "C:\Error logger\venv\lib\site-packages\django\db\models\base.py", line 932, in _prepare_related_fields_for_save raise ValueError( Exception Type: ValueError at /add-solution/4/my-name-is-anirudh Exception Value: save() prohibited to prevent data loss due to unsaved related object 'log'. Also can someone explain what does the below do? I found that this is needed for slug urls.. But I don't understand what is super().save() def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.solution) super().save(*args, **kwargs) Also what is the error that I am getting? models.py class Solutions(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, blank=True, null=True) solution = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.solution) super().save(*args, **kwargs) class Meta: verbose_name = ("Solution") verbose_name_plural = ("Solutions") def __str__(self): return f" {self.solution} " views.py def … -
Django ManyToManyField post not working in drf
model class DesignerProduct(models.Model): title = models.CharField(max_length=500, default=None) descripton = models.CharField(max_length=500, default=None) price = models.CharField(max_length=500, default=None) editions = models.CharField(max_length=500, default=None) verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) user = models.ForeignKey( to=Login, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True ) collection = models.ForeignKey( to=DesignerCollection, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True ) categories = models.ManyToManyField(DesignerCategories, related_name='designerproduct', blank=True) serializers class DesignerProductSeriali designerproductmedia = DesignerProductMediaSerializer(many=True, read_only=True) user = serializers.PrimaryKeyRelatedField(queryset=Login.objects.all(), many=False) collection = serializers.PrimaryKeyRelatedField(queryset=DesignerCollection.objects.all(), many=False) user_name = serializers.CharField(source='user.name', read_only=True) user_photo = serializers.CharField(source='user.display_photo', read_only=True) class Meta: model = DesignerProduct fields = ('id', "user", "categories", "collection", 'created_at', 'designerproductmedia', 'title', 'descripton', 'price', 'editions', 'verified', 'user_name', 'user_photo') depth = 1 data after upload { "id": 11, "user": 9, "categories": [], "collection": 6, "created_at": "2021-06-05T17:03:52.807755Z", "designerproductmedia": [ { "file": "designer/products/74647.jpg", "id": "38", "firework": null } ], "title": "hello there", "descripton": "hello there", "price": "10", "editions": "10", "verified": false, "user_name": "soubhagya pradhan", "user_photo": "profile/52319.jpg" } Here i am omplmenting django manyToMany relation and sending categories like [1, 2, 3] But, after successfull post category list comes empty . How to fix that ? Please take a look In drf also not showing please check this image -
How to style django forms
I'm using the django standar forms, is there any way to style this without using model forms class DeliveryForm(forms.Form): full_name = forms.CharField(max_length=50) email = forms.EmailField() phone = forms.CharField(max_length=25) address = forms.CharField(max_length=100) city = forms.CharField(max_length=50) postal = forms.CharField(max_length=10) this is my template as well <form action ="" method='post'> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Next"> </form> -
Adding Context to Navbar HTML Django Project
I am trying to add context to navbar.html but it is not rendering/ showing the required information. Here is the models.py: class Information(models.Model): github = models.URLField(blank=True, null=True) linkedin = models.URLField(blank=True, null=True) facebook = models.URLField(blank=True, null=True) twitter = models.URLField(blank=True, null=True) here is the view.py: #Trial 1 def home(request): template_name = 'blog/navbar.html' info = Information.objects.first() context = { 'info': info, } return render(request, template_name, context) #Trial 2 class Home(DetailView): model = Information template_name = 'blog/navbar.html' # <app>/<model>_<viewtype>.html context_object_name = 'info' Here is the HTML: <a href="" class="nav-link waves-effect">{{info.facebook}} <i class="fab fa-facebook-f"></i> </a> My Qustion: Why is the {{info.facebook}} not printing what am I missing? How should I fix it? In the URLs I did not add anything because I am sending the context to navbar which will be appearing on every page not a specific page -
How to customise the validation rules of django-allauth Login/Signup forms?
I am using django-allauth for the user authentication part of my application. I wanted to customise the validation rules for my login, ex. blacklisting certian domain name for email id. But I am not able to figure out how should I do that. I tried to make a custom login form(inherited from forms.Form class) and write the rules in that, but I guess think that allauth processes the login request with its adapter. Due to this I was getting a TypeError: __init__() got an unexpected keyword argument 'request'. I am not able to understand the flow in which the methods are being called in the adapter. Please help me implement the custom validation rules in django-allauth forms. Or else how should I inherit the LoginForm class in the allauth package so that I can add my validation rules. -
How do I integrate base.html in the main page
Im having trouble extending base.html. ill have the templates below but the problem is the webpage only shows the base.html template when i extend base.html to the main page which is item_list.html and it doesnt show the content i have on the main page. Thank you in advance for any form of guidance item_list.html {% extends "base.html" %} {% block content %} <h2> Here is the list of items </h2> {% for item in items %} {{ item }} {% endfor %} {% endblock content %} base.html <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html> -
Formatting in Django models
I am working in django where the I have some models in my model.py file and accordingly data is added by the django-admin and the data is kind of in the type of the messages we receive in messengers i.e, It has some properties like: 1.part of the text is a link. 2.part of the text is in bold/italic. For formatting the messages like this, is there any way we can implement this or any preexisting Field like this? (Where I can style my text accordingly like the way whatsapp works i.e, it detects the links and gives ability to bold, italicize the text etc...) -
Redirecting user to dynamic url after google login using django allauth
I am using google sign in to authenticate users using django allauth. There is no need to log the user in prior to them trying to interact with the website, which happens at https://www.example.com/example/5 where 5 is just an id to a model instance in my database. After user login, I would like to redirect the user to the same page they are on. Would it be possible to do this either through passing the model id (5 in this example) through the google credentials and receive the number back at the /accounts/google/login/callback/ callback, or something similar? Or perhaps there is way using django allauth. This question is close to what I need, but I don't know how to get access to the model ID using this approach. Django-Allauth, Multiple login redirect url # In myapp/adapter.py from allauth.account.adapter import DefaultAccountAdapter class AccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): url = super(AccountAdapter, self).get_login_redirect_url(request) user = request.user ''' # pseudocode, change it to actual logic # check user role and return a different URL role = get_user_role(user) if role == 'student': url = student_login_redirect_url if role == 'teacher': url = teacher_login_redirect_url ''' return url # settings.py ACCOUNT_ADAPTER = 'my_app.adapter.AccountAdapter' -
Display django field choices in a particular order
I am using django models and one of the charfields has a list of choices like class Ster(models.Model): STER_PRODUCTS_CATEGORY = [ ('Steam', 'Steam'), ('ETO', 'ETO'), ('Plasma', 'Plasma'), ('LTSF', 'LTSF'), ('Heat', 'Heat') ] ster_prod_name = models.CharField(max_length=100) ster_prod_category = models.CharField( max_length=100, choices=STER_PRODUCTS_CATEGORY, default='None') Whenever I add an item to any of the category, that particular category is shown first on the webpage. For ex, if i add an item to the category Heat, that category is displayed first. I am looping through the list. My views.py function looks like this ster_catprods = Ster.objects.values('ster_prod_category', 'id') ster_cats = {ster_item['ster_prod_category'] for ster_item in ster_catprods} for ster_cat in ster_cats: ster_prod = Ster.objects.filter(ster_prod_category=ster_cat) m = len(ster_prod) mSlides = m // 4 + ceil((m / 4) - (m // 4)) ster_prods.append([ster_prod, range(1, mSlides), mSlides]) My HTML Template snippet is like this <section class="container"> <h4 style="margin: 1em auto">1.STER</h4> <div class="row"> {% for p,range,mSlides in ster_prods %} <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 col-xl-4" data-aos="zoom-in-up" style="margin: 1em auto"> <h4 class="category-title my-4">{{p.0.ster_prod_category | safe}}</h4> {% for i in p %} <h6 class="product_title">{{i.ster_prod_name | safe }}</h6></a> {% endfor %} </div> {% endfor %} </div> </section> how do i get to display the categories in a particular order like the way i want? The …