Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Paypal integration - Rendering button not working when changing language
I've integrated Paypal to my website and everything worked as expected. However when i added a new language (greek) i got a problem when pressing pay with paypal button. When change back to english everything works and button is rendering with no probs. The error i got from paypal is: Since is the first attempt to work with paypal i would appreciate any help if you can give me any hint on the below error or any idea on how to troubleshoot. Many Thanks -
I am confused when i should use these
I am really confused about when I should use these, urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django - how to check if email is already exists
I need to show error message if email is already exists, but I can't check if new customer trying to enter used email. I am using UserChangeForm. forms.py class UserChangeForm(forms.ModelForm): class Meta: model = Account fields = ('email', 'fname', 'lname', 'phone','bday', 'country', 'gender','picture') # email = forms.CharField(widget=forms.EmailInput(attrs={'class':'form-control'})) # fname = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Name'})) # lname = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Surname'})) phone = PhoneNumberField(widget=PhoneNumberPrefixWidget(initial='GE'), required=False) phone.error_messages['invalid'] = 'Incorrect international code or Phone number!' # bday = forms.CharField(widget=DatePickerInput(attrs={'class':'form-control', 'placeholder':'Birth Date'})) # country = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Country'})) # gender = forms.ChoiceField(choices=Account.GENDER_CHOICES, widget=forms.Select(attrs={'class':'regDropDown'})) # picture = forms.FileField(widget=forms.ClearableFileInput(attrs={'class':'form-control'})) def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] views.py @login_required def edit_profile(request, id): account = Account.objects.all() # context['DATA_UPLOAD_MAX_MEMORY_SIZE'] = settings.DATA_UPLOAD_MAX_MEMORY_SIZE user = Account.objects.get(id=id) form = UserChangeForm(instance=user) if request.method == "POST": form = UserChangeForm(request.POST, files=request.FILES, instance=user) if form.is_valid(): for info in account: if info.email == form.email: messages.warning(request, 'email already exists.') data = form.save(commit=False) data.is_active = True data.save() return redirect('account:editprofile', id) context = {'form':form, 'user':user} return render(request, 'edit_profile.html', context) I saw some examples but they don't work in my case as I do. Also, I find … -
There Is No Django HTML language
Hay, i'm learning python, and in The Django Tutorial: While Using Django Templates To View Something in the Server..in the html File When I Try To Select The Django Html Language it doesn't Exist: Like This: enter image description here OS : Windows 7 64bit Python Version: 3.8.10 Django Version : 3.2.5 VS Code Version : 1.57.1 I Wish Someone Can Help. -
What should I add in my views.py if I want to accept complaints from different users in my complaint management system in django
I am making a complaint management system where different users can log in and add complaints to the system. I need to make a page where the user can add complaints that will be saved in the admin panel but idk how to do it. I have created the model and the template but idk what else to add in the views or the forms. I've tried a bunch of different things but none seem to work. can someone please tell me how to do it? Models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title Template: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="email" class="form-control col-lg-10 comp-title-field" placeholder="Complain title"> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <textarea class="form-control comp-textarea" rows="7" placeholder="Enter text here"></textarea> <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" class="btn btn-secondary save-btn" value="submit"><i class="fas fa-save"></i> Save</button> </form> </div> It needs to look like this: Please help me with this... I've been at this the whole day and Idk what else … -
How to use another template engine in Django
I want to create an engine that i will later use when working with Template instances. I do not want to define it in the settings due to the fact that the logic defined in it should not be distributed everywhere, but only in specific cases. Here's what I did: from django.template.engine import Engine class ModelEngine(Engine): def find_template(self, name, dirs=None, skip=None): # some another logic to get a template instance ... engine = ModelEngine() # Usage template_code = "{% include \"some_template.html\" %}" Template(template_code, engine=engine).render(Context()) Is this solution correct? Is there something wrong with not inheriting from BaseEngine, but from Engine? If yes, please advise something. -
Django failed to insert data that has a foreign key relation
I have two tables: Company and Address. The Company table has the basic contact information of the company, and the Address contains the address and geolocation of the company. These two tables are connected with a foreign key named "company_name," which is neither a primary key of both tables. I inserted some mock data of a company named "FF2" into the company table, it went great. However, when I attempted to insert "FF2" with its mock address into the Address table, I failed and received this: company_name: ["Incorrect type. Expected pk value, received str."] I tried every solution I found online, but none of them worked. Please help and be specific as possible, thank you so much!! model.py: class Address(models.Model): city = models.CharField(max_length=200) state = models.CharField(max_length=200) zip = models.CharField(max_length=20) address1 = models.CharField(max_length=200) address2 = models.CharField(max_length=200, blank=True, null=True) company_name = models.ForeignKey('Company', models.DO_NOTHING, db_column='company_name') lat = models.DecimalField(max_digits=50, decimal_places=6) long = models.DecimalField(max_digits=50, decimal_places=6) class Meta: managed = False db_table = 'address' class Company(models.Model): company_name = models.CharField(unique=True, max_length=200) contact_name = models.CharField(max_length=100) phone = models.CharField(max_length=100) email = models.CharField(max_length=100) website = models.TextField() class Meta: managed = False db_table = 'company' views.py: class AddressView(APIView): serializer_class = AddressSerializer def get(self, request): address = [ {"city": address.city, "state": address.state, … -
how to validate wehther the URL given is from a specific domain or not in django
I have a model: class Profile(models.Model): social_github = models.URLField(blank=True, null=True) social_twitter = models.URLField(blank=True, null=True) social_linkedin = models.URLField(blank=True, null=True) social_youtube = models.URLField(blank=True, null=True) I want to validate the URL to their respective domain for example, the user should only be able to submit the URL of the domain `GitHub in the Github field -
Multiple forms in one Django class-based view with one submit button
I have 2 models, User and Profile. User is Django's baked-in user model, and has a username, and the email the user used to sign up. Profile is the model shown below: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True, null=True) bio = models.TextField(blank=True, null=True) email = models.EmailField(blank=True, null=True) def __str__(self): return f'{self.user.username}\'s Profile' def get_absolute_url(self): return reverse('profile-detail', kwargs={'pk': self.user.pk}) The detail view for these profiles can be accessed using the following URL pattern: # ... path('profiles/<int:pk>', user_views.ProfileDetailView.as_view(template_name='users/profile.html'), name='profile-detail'), # ... What I want to do is to create an update view that allows a user to update both their User details, and their Profile details, with a URL pattern that looks like this: path('profiles/<int:pk>/update', user_views.ProfileUpdateView.as_view(template_name='users/profile_form.html'), name='profile-update'), I know that such an update view can be created for one model using Django's generic UpdateView, but I haven't been able to figure out how I can accomplish this for 2 models. -
How to grey out a button after buttonpress in Django until the associated function returns
When I click on my button an associated function in my views.py is executed. After execution a result page is rendered. However, if I click on the button multiple times the website shows a runtime error: RuntimeError: main thread is not in main loop To avoid this error and unnecessary parallel execution I want to grey out (disable) the button on buttonpress and make it active after the result page is shown (result page extends the normal page, so the button is still there). How do I achieve this? -
How do I use a field in another HTML page in my current HTML page's field to carry out a calculation using JS? It's a Django project
I have three models, Student, Camp, Activity: class Student(models.Model): id_pattern = RegexValidator(r'BSK\/[0-9]{2}\/[0-9]{4}', 'Enter Your ID properly!') student_id=models.IntegerField(primary_key=True, validators=[id_pattern]) name=models.CharField(max_length=70) roll_number=models.IntegerField(max_length=3) def __str__(self): return self.student_id class Camp(models.Model): student_id=ForeignKey(Student, on_delete=CASCADE) batch=models.CharField(max_length=10, default=None) fee=models.DecimalField(max_digits=7, decimal_places=2) class Activity_type(models.Model): activity_type=models.CharField(max_length=20, blank=True) def __str__(self): return self.activity_type class Activity(models.Model): student_id=ForeignKey(Student, on_delete=CASCADE) activity_type=ForeignKey(Activity_type, on_delete=CASCADE) discount=models.DecimalField(max_digits=4, decimal_places=2) final_amount=models.DecimalField(max_digits=7, decimal_places=2) The respective views: def student_view(request): if request.method=='POST': fm_student=StudentForm(request.POST) if fm_student.is_valid(): fm_student.save() fm_student=StudentForm() return render(request, 'account/student.html', {'student_form':fm_student}) else: fm_student=StudentForm() return render(request, 'account/student.html', {'student_form':fm_student}) def activity_type_view(request): if request.method=='POST': fm_activity_type=Activity_Type_Form(request.POST) if fm_activity_type.is_valid(): fm_activity_type.save() fm_activity_type=Activity_Type_Form() return render(request, 'account/activity_type.html', {'activity_type_form':fm_activity_type}) else: fm_activity_type=Activity_Type_Form() return render(request, 'account/activity_type.html', {'activity_type_form':fm_activity_type}) def activity_view(request): if request.method=='POST': fm_activity=ActivityForm(request.POST) if fm_activity.is_valid(): fm_activity.save() fm_activity=ActivityForm() return render(request, 'account/activity.html', {'activity_form':fm_activity}) else: fm_activity=ActivityForm() return render(request, 'account/activity.html', {'activity_form':fm_activity}) def camp_view(request): if request.method=='POST': fm_camp=CampForm(request.POST) if fm_camp.is_valid(): fm_camp.save() fm_camp=CampForm() return render(request, 'account/camp.html', {'camp_form':fm_camp}) else: fm_camp=CampForm() return render(request, 'account/camp.html', {'camp_form':fm_camp}) Now, I want to use JavaScript to calculate the final_amount (Activity class/model) field's value but the basis for that calculation would be the fields, fee from Camp model, which will be on a separate HTML page, and activity_type and discount fields of Activity model. So how do I do that? I can capture the elements on the single page, but how do I use fee field's value and activity_type and discount … -
Multiple file uploading in django with session management
I am trying to use the multiupload2 library along with form wizard in django. The issue is that the input field tends to replace the fields on new files being selected and I also need the cancel/delete functionality on the input fields. In order to maintain the input field states,I can use ajax but that requires me to trigger the set_step_files function of the form wizard which I can't because ajax requires static methods, same goes for the delete functionality. Is there a way to handle this without using ajax? -
How can I get the `pk` from the endpoint while doing object level validation?
I have an endpoint as api/v1/controller/{pk}/device Now I want to add a device to the controller object while I am doing the object level validation by acquiring the {pk} of the controller object:- def validate(self, data): data['device'] = self.(do something to get the PK present in the endpoint) data.full_clean() return data Is there any way I can get the pk/id from the endpoint while doing an object level validation for performing a create operation under the controller resource. -
How to use data posted for one view into another view in django rest
I am working on a project in which user enters some ranges like (starting_date, ending_date, starting_roll_num, ending_roll_num, and subject) and it queries the DB and returns a csv file but i want to add another feature which enables the user to also get the remaining data after he has entered the ranges and downloaded the first file but for this I have to make an other function, the problem is how will I use the data posted on the first function. Here is my code: serializer.py class DatasetGeneratorSerializer(serializers.Serializer): start_roll = serializers.IntegerField() end_roll = serializers.IntegerField() start_date = serializers.DateField() end_date = serializers.DateField() subject = serializers.IntegerField() def create(self, validated_data): pass views.py @api_view(['POST']) @authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def attendance_datasetgenerator(request): serializer = DatasetGeneratorSerializer(request.data) start_roll = serializer.data['start_roll'] end_roll = serializer.data['end_roll'] start_date = serializer.data['start_date'] end_date = serializer.data['end_date'] subject = serializer.data['subject'] att= Attendance.objects.filter(date__range=(start_date,end_date), student__pk__range=(start_roll,end_roll), subject__exact=subject) df1 = DataFrame(att.values()) path = 'attendance_dataset.csv' csv1 = df1.to_csv('attendance_dataset.csv') response = HttpResponse(csv1, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=file1.csv' return response -
Can't have a slug with the word `media` in it. Django
Setup I have a very simple app where the main page display a list of items and if you click on an item you go the the item detail. Here is a part the model for such item: # projects/models.py class Project(models.Model): ... title = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from="website_title", always_update=True) ... As you see the slug for the item is determined based on the name (it removes spaces, special characters, etc.) Now, in my urls.py I have the following: # projects/urls.py urlpatterns = [ path("", ProjectListView.as_view(), name="home"), path("<slug:slug>", ProjectDetailView.as_view(), name="project"), ] Problem The problem is that if a project name contains the word media in it (in the beginning) then the resulting path will return an error. For example, if a project is called MediaCMS then the server will try the following url https://builtwithdjango.com/mediacms, but it will return an error (below). The work around I found is to add underscore to the name of the project (i.e. _MediaCMS). The issue is obviously due to some sort of mix and match between the project slug and the MEDIA_URL, which for me is the following: # builtwithdjango/settings.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media/") Note Interestingly, this is not an issue, … -
Django Querset Extract PKs
I have the following code. queryset = Registry.objects.filter( epas_id__contains=uuid_obj_id ).values_list('pk', flat=True) Based on my data, this correctly returns the following: <QuerySet [UUID('d9a0977c-5bc0-4667-af24-5e95b83761d4'), UUID('b2d0f086-0a55-44cc-b1ba-3ebf598d24ae')]> But what I want to do is extract just the values of pk in a list, so something like this: ['d9a0977c-5bc0-4667-af24-5e95b83761d4', 'b2d0f086-0a55-44cc-b1ba-3ebf598d24ae'] Any thoughts and help on how I can achieve this would be appreciated. -
deployment with apache collecting statics already 24hours
Im worried about collecting my staticfiles. When I was trying to deploy my project and I put command "python manage.py collectstatic" its asked me something like "Am I sure that im runing this command in virtual environment ?" I typed "yes " because I had acivated it, and then I think started to loading statics but it takes already about 24h and screen didnt changed since that time. Is it ok ? I have quite advanced frontpage from template but i dont think that much... Console looks like this and keep scrolling down with "new Y" Y Y Y Y Y[] Can hear very well my fan from CPU and ubuntu consol keep scrolling down itselfs all the time which is indicating me that isn't frozen. Should I cancel it or wait untill its will finish? -
Whenever I run command "python maanage.py runserver" It shows me OSError: [WinError 123]
Whenever I run command python manage.py runserver this errors are showing OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' and I don't know why that code is not working I think it is because of the version?. This is a traceback error. I don't know what it is. Can someone explain to me why is this error is occurring? (venv) C:\python\Work\Project\45.MULTIFACTOR OPINION MININGMULTIFACTOR OPINION MINING\MULTIFACTOR OPINION MININGMULTIFACTOR OPINION MINING\MULTIFACTOR OPINION MININGMULTIFACTOR OPINION MINING\CODE\opinion mining\opinionmining>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\users\user\appdata\local\programs\python\python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\user\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Envs\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\user\Envs\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\users\user\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load … -
Adding a Token to Django request
Could anybody help me add an api AUTH token to my request, I'm unsure how to add non Django AUTH token to the request, I want to be able to insert the AUTH token into my request that way every time I use the website I wont have to constantly respond to the SMS message the api makes me do. Here is the code I have so far from robin_stocks import robinhood as RH @login_required def home(request: HttpRequest, *args, **kwargs): """ The landing page for the user, after they log in should contain a bunch of deets """ if (request.COOKIES['ul.token']): positions = RH.account.get_all_positions() print(positions) else: token = RH.authentication.login(username=env.RHemail, password = env.RHpassword) request.COOKIES['ul.token'] = token.access_token context = {'positions' : positions} return render(request, 'home.html', context) I saved it as ul.token because when I logged into my robin hood account that's what the tokens name was in my cookies. I probably missed the mark on this one as well PS: This right now is a personal project just for fun, so that explains my docstring (which is what I think """ """ is called) -
Django querysets. How to prefetch only unique?
Models: class House(Model) class Flat(Model): house = ForeignKey(House, related_name="houses") owner = ForeignKey(User) class User(Model) queryset: queryset = User.objects.prefetch_related( Prefetch("flats", queryset=Flat.objects.select_related("houses")) And then flats: {% for flat in user.flats.all %} <p>№ {{ flat.number }}, {{ flat.house.name }}</p> {% endfor %} It's fine. But for houses I need only unique ones {% for flat in user.flats.all %} <p>House {{ flat.house.name }}</p> {% endfor %} But this template gives me ALL houses, with duplicates. How can I avoid duplicates, any ideas? I tried .distinct() but it's dosen't work, looks like I using distinct() wrong or etc. -
Django models.DateTimeField invalid format
I'm trying to import database rows into Django models. The date format in the database I'm using is '%Y/%m/%d %H:%M:%S', and this is the error I get when I try to import the data: . . . File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1406, in get_prep_value value = super().get_prep_value(value) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1266, in get_prep_value return self.to_python(value) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1388, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: ['“2013/01/01 07:57:25.689” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I have this line my settings.py: DATETIME_FORMAT = '%Y/%m/%d %H:%M:%S' How do I change the default format to be the same format as my data? Thank you! -
How to manage User Related operations on client servers which are Authenticated by A Central Auth Server in Django
I developed a Central Authentication Server with SimpleJWT for a company which have multiple websites and the users of all the websites will be authenticate through the Central Authentication Server. Now, here is the scenario- The Auth Server will have the User Table with UUID, phone/email and Password which will be used for authentication. On the other hand, suppose an ecommerce site have database tables Products, transactions etc. Now, how can I implement the user related operations like buy, sell, transactions etc. on the ecommerce site as I don't have any user table here. -
How to set specific conditions in models.py while entering data in admin panel?
room_category = models.ForeignKey(Cat, on_delete=models.CASCADE) number = models.IntegerField(unique=True) people = models.IntegerField() picture = models.ImageField(upload_to = 'room/', null=True, blank=True) actual_price = models.IntegerField() offer_price = models.IntegerField() def __str__(self): return '%d : %s with People : %d' % (self.number, self.room_category, self.people) I want to set a condition in offer_price table that offer_price < actual_price. It should show an error while entering data in the admin panel itself. -
Wrong size in bytes being displayed using BytesIO in Django
I am trying to validate images before they are uploaded to the database using django , but cant seem to get accurate size of images no matter what I do view.py: def upload_image(request): #used to upload images in document_upload c = main.objects.get(username = request.session['username']) unq_id = c.unq_id if request.method == 'POST': images = request.FILES.getlist('image') name = request.POST['name'] for x in images: img = Image.open(x) img_file = BytesIO() img.save(img_file, 'jpeg') image_file_size = img.tell() if image_file_size > 150 * 1024: print(image_file_size) failure = "image needs to be lesser dimenstion than 150kb" return render(request, 'Main/document_upload.html', {'failure':failure}) else: print(image_file_size) fs = FileSystemStorage() filename = fs.save(x.name, x) Doc1 = Doc(user_id = unq_id, upload = x, name = name) Doc1.save() success = "You have successfully added documents, proceed to 'My documents' to see your documents" return render(request, 'Main/document_upload.html', {'success':success}) While printing print(image_file_size) I seem to be getting a much lesser value , than the size shown in it's properties example print(image_file_size) shows 1295 while in reality the size is 8537 How do I solve this ? thank you -
django orm multiple filter on same many to many fields
class Book(models.Model): title = models.CharField(max_length=50) authors = models.ManyToManyField(Author) class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) I want to find Books containing atleast the authors with first_name and last_name in the below list without using for loop(mentioned below) or raw query. authors = [{ 'first_name' : 'Test', 'last_name' : 'user1', }, {'first_name' : 'Tester', 'last_name': 'user2' } ] queryset = Book,objects.all() for i in authors: queryset = queryset.filter(authors__first_name=i.get('first_name',None), authors__last_name=i.get('last_name',None))