Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
make form look like an excel table
I made this form: the form: AgregatsFormset = inlineformset_factory(Canva, Bilan, fields=('agregat', 'SCF', 'mois1', 'mois2', 'ecart1', 'evolution1', 'finmois1', 'finmois2', 'ecart2', 'evolution2'), can_delete=False, max_num=5) html: {% for bilan_form in form.forms %} {% for fidden_field in bilan_form.hidden_fields %} {{ hidden_field.errors }} {% endfor %} <table> {{ bilan_form.as_table }} </table> {% endfor %} the form look like this how do i make it look like an excel table ? : like this -
Implement Django REST TokenAuthentication for Multiple User Model
I need to implement TokenAuthentication using Custom user model Consumer & Merchant (The default User model still exists and is used for admin login). I've been looking on official DRF documentation and days looking on google, but I can't find any detailed reference about how to achieve this, all of the references I found using default User or extended User models. class Consumer(models.Model): consumer_id = models.AutoField(primary_key=True) token = models.UUIDField(default=uuid.uuid4) email = models.CharField(max_length=100, unique=True, null=True) password = models.CharField(max_length=500, default=uuid.uuid4) class Merchant(models.Model): merchant_id = models.AutoField(primary_key=True) token = models.UUIDField(default=uuid.uuid4) email = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=100) password = models.CharField(max_length=500, default=uuid.uuid4) Settings.py INSTALLED_APPS = [ ... 'rest_framework', ... REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser' ] } I'm also using @api_view decorator with function-based views: @api_view(['POST']) @renderer_classes([JSONRenderer]) def inbound_product(request, pid): product = MerchantProduct.objects.get(product_id=pid) -
Add SECRET_KEY to Heroku
When I type heroku config:set SECRET_KEY='MySecretKey' on my Powershell I got this error: 'SomeOfMyCharacterOnMySecretKey' was unexpected at this time. Please tell me if you know how to solve this. Thank you -
Django: how can i change models variable value through template
I want to add function to change is_shown value when the button is pressed. It should be in view but I don't know where exactly. MODEL class Coupon(models.Model): name = models.CharField(max_length=255) price = models.PositiveIntegerField() is_shown = models.BooleanField(default=False) is_used = models.BooleanField(default=False) pub_date = models.DateTimeField(auto_now_add=True) VIEW class CouponListView(ListView): model = Coupon paginate_by = 10 TEMPLATE <ul> {% for coupon in object_list %} {% if not coupon.is_used %} <li> {% if coupon.is_shown %} {{ coupon.name }} {% else %} {{ coupon.price }} <input type="submit" value="show" name="show_coupon"> {% endif %} </li> {% endif %} {% endfor %} </ul> -
DRF serializer doesn't save instance to the db
Views class AuthDataViewSet(ModelViewSet): queryset = AuthData.objects.all() serializer_class = AuthDataSerializer def create(self, request, *args, **kwargs): serializer_data, headers = create_auth_data(self, request.data, {'request': request}) # returning response with the data create_auth_data function def create_response_data(view, data: dict = None, context: dict = None): # I calling the viewset methods below serializer = view.get_serializer(data=data, context=context) serializer.is_valid(raise_exception=True) view.perform_create(serializer) headers = view.get_success_headers(serializer.data) return serializer.data, headers I got the correct serializer.data, no errors and pure data, but the instance didn't saved to the database. -
make virtual payment in django
hello thanks for your visiting i have to develop my Django web app and I went to make a virtual payments between acount like point exchange my question is it secure if i do it using method Post and forms ? example to understand me models.py class Profile(models.Model): name=models.CharField(max_length=50) user =models.OneToOneField(User,verbose_name=_("user"),on_delete=models.CASCADE) funds=models.IntegerField(default=0) class Product(models.Model): name=models.CharField(max_length=50) price=models.IntegerField() profile = models.ForeignKey(Profile,on_delete=models.CASCADE) forms.py class ProductForm(forms.ModelForm): class Meta: model = Order fields ='__all__' exclude=('profile',) view.py def product_order(request,id): form=ProductForm(instance=request.user) product_detail=Product.objects.get(id=id) id_seller=product_detail.profile.id if request.method == 'POST': form=ProductForm(request.POST,instance=request.user) if form.is_valid(): p=Profile.objects.get(user=request.user) p.funds=p.funds-product_detail.price if p.credit>=0: p.save() k=Profile.objects.get(id=id_seller) k.funds=k.funds+product_detail.price k.save() return redirect(reverse('core:product')) return render(request,'user/form.html',{'form':form}) -
Django customed user model createsuperuser error
I'm newb to python django. I am making a small web page. Here is a piece of code i'm running. I want to make cumtom user model and use it to resigter with music genre, instrumet and nickname. But with this code, even i did all the migrations, doesn't work well. After the email input, an error is keep occuring. The error is <django.db.utils.OperationalError: no such column: accounts_user.genre>. Please help....😥 <models.py> from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class UserManager(BaseUserManager): def create_user(self, email, genre, nickname,instrument, name, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), genre=genre, nickname=nickname, instrument=instrument, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,nickname, email,password): user = self.create_user( email, password=password, nickname=nickname, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email', max_length=255, unique=True, ) objects = UserManager() genre=models.CharField(max_length=100) instrument=models.CharField(max_length=10, default='') nickname = models.CharField(max_length=100, default='') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['instrument'] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin and here is my views.py <views.py> from django.shortcuts import render, redirect from .models import User from django.contrib import auth def signup(request): … -
How to add image with the specific user with different API in django rest framework
How to add image with the specific user in django rest framework Pass user's id and image as a parameter in API -
Dynamically populated dropdowns in table with Django
I have developed a small interface to list the projects with Django. Each project has multiple versions. I would like to create a table and in each row I would like to have the following items. Project Name Project Description A dropdown button to select the desired version A button to open that specific project and that specific version I am fine with item 1, 2 and 4 but I am struggling to create the dropdown after querying the list of versions. This is my project.html <table> <tr> <th>ID</th> <th>Name</th> <th>Description</th> <th>Version</th> </tr> <!-- {% for project in projects %} --> <tr> <td>{{project.id}}</td> <td>{{project.projectName}}</td> <td>{{project.projectDescription}}</td> <td>Dropdown</td> <td><form action="{% url 'builder' project.id %}" method='GET'><button type='submit'>Open</button></form></td> </tr> <!-- {% endfor %} --> </table> This is my model.py class Project (models.Model): id = models.AutoField(primary_key=True) projectName = models.CharField(max_length=100) projectDescription = models.CharField(max_length=500) created_by = ForeignKey(User, on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.projectName class ProjectVersion (models.Model): id = models.AutoField(primary_key=True) versionNumber = models.IntegerField() versionName = models.CharField(max_length=100) project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) versionDescription = models.TextField(default='') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): vName = self.project.projectName + " " + self.versionName return vName and this is my views.py class ProjectsList(TemplateView): template_name = "projects.html" def get(self, request, *args, **kwargs): context = self.get_context_data() … -
How to activate a user when user verify his/her phone number using Twilio in Django? If user is not verified how to deactivate a user?
How to activate a user when the user verifies his/her phone number using Twilio in Django? If the user is not verified how to deactivate a user? Here is My code. in forms.py file class CreateUserForm(UserCreationForm): email = forms.EmailField() phone = forms.CharField(max_length=17) country_code = forms.CharField(max_length=3, initial='+19') class Meta: model = User fields = ['username', 'email', 'phone', 'password1', 'password2'] in views.py def signupPage(request): form = CreateUserForm() # if request.method == 'GET': # return render(request, 'user/signup.html') if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() # ==================================== request.session['phone'] = form.cleaned_data['phone'] request.session['country_code'] = form.cleaned_data['country_code'] authy_api.phones.verification_start( form.cleaned_data['phone'], form.cleaned_data['country_code'], ) return redirect('token_validation') # ==================================== context = {'form': form} return render(request, 'user/signup.html', context) in views.py Is there any problem in token_validation function? def token_validation(request): if request.method == 'POST': form = TokenForm(request.POST) if form.is_valid(): verification = authy_api.phones.verification_check( request.session['phone'], request.session['country_code'], form.cleaned_data['token'] ) if verification.ok(): request.session['is_verified'] = True messages.info(request, 'Your Phone Number is Verified, Please Enter Your Information.') user.is_active = True user.save() return redirect('verified') else: for error_msg in verification.errors().values(): form.add_error(None, error_msg) else: form = TokenForm() return render(request,'user/token_validation.html', {'form': form}) Here I am getting an error user.is_active = True NameError: name 'user' is not defined when I am trying to make the user … -
How to get value of ForeignKey in views.py?
I have below models.py and views.py in Django. How can i print the value of ForeignKey in views.py? models.py class student(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=100, blank=True, null=True) phone_number = models.ForeignKey(tell,on_delete=models.SET_NULL, null = True,blank=True) def __str__(self): return self.name class tell(models.Model): phone_number = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return self.phone_number views.py phones = student.objects.values('phone_number') phone = list(phones) for ob in phone: print(ob) This prints only id but i want the value of foreign key. -
Most Efficient Way to Convert Panda Rows to a Django Model
I'm currently trying to take multiple pandas dataframes and convert them into django model objects. My current code looks something like this: for index, row in df.iterrows(): defaults = {} name = row[('Unnamed: 0_level_0', 'Player')] defaults['player'] = Player.objects.get_or_create(name=row[('Unnamed: 0_level_0', 'Player')], team=team)[0] defaults['pass_att'] = float(row[('Passing', 'Att')]) defaults['pass_yds'] = float(row[('Passing', 'Yds.1')]) defaults['pass_td'] = float(row[('Passing', 'TD')]) . . . home_name_to_default[name] = defaults I create all the objects at the end using a bulk create method call. This code is quite slow as I am iterating over tens of thousands of dataframes. However, I do not know of a more efficient way to write this. Are there any ways that are more efficient? -
Categorizing Posts in Django?
I am having a problem in categorize Posts. I have categories in Post Model, Please help me solve this issue! MODELS.PY html= "html" css= "css" python= "python" javascript = "javascript" Lang=( (html,"HTML"), (css,"CSS"), (python,"PYTHON"), (javascript,"JAVASCRIPT") ) Broilerplate = "Broilerplate" Simple_Tags = "Simple Tags" Elements = "Elements" Webpages = "Webpages" Category = ( (Broilerplate,"BROILERPLATE"), (Simple_Tags,"Simple tags"), (Elements,"Elements"), (Webpages,"Webpages") ) class Post(models.Model): title = models.CharField(max_length=75) subtitle = models.CharField(max_length=150) language_1 = models.CharField(max_length=100, choices=Lang, default=html) content_1= models.TextField(blank=True) language_2 = models.CharField(max_length=100, choices=Lang,blank=True) content_2= models.TextField(blank=True) language_3 = models.CharField(max_length=100, choices=Lang,blank=True) content_3= models.TextField(blank=True) language_4 = models.CharField(max_length=100, choices=Lang,blank=True) content_4= models.TextField(blank=True) language_5 = models.CharField(max_length=100, choices=Lang,blank=True) content_5= models.TextField(blank=True) category= models.CharField(max_length=100, choices=Category, default=Broilerplate) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title # def update(self): # updated_at = timezone.now() # self.save(updated_at) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) VIEWS.PY def search_by_category(request, category): if request.post.objects.filter(pk=request.post.id).first().category == 'Broilerplate': nor = request.post.objects.filter(pk=request.post.id).first().category print(nor) posts = Post.objects.filter(category='Broilerplate') category = posts.first().category print(category) context = {'posts': posts, 'title': category , 'category': category} return render(request, 'category.html', context) else: context = {'title': category , 'category': category} return render(request, 'category.html', context) URLS.PY urlpatterns = [ path('html/',PostListView.as_view(), name='CodeWriter_Homepage'), path('python/',views.CodeWriter_homepage_python, name='CodeWriter_Homepage_python'), path('search/', views.search, name='search'), path('categroize-by/<str:category>/', views.search_by_category, name='search_by_category'), path('post-details/<int:pk>/',PostDetailView.as_view(), name='Post_details_page'), path('post-update/<int:pk>/',PostUpdateView.as_view(), name='Post_update_page'), path('post-delete/<int:pk>/',PostDeleteView.as_view(), name='Post_delete_page'), path('user/<str:username>/', UserPostListView.as_view(), name='user-post'), path('new-post/',PostCreateView.as_view(), name='New-post_page') ] CATEGORY.html How can I get … -
How to list multiple uploaded files in html template
I successfully made a form that takes and uploads multiple files. When I check the request.FILES I can see that they have the following files listed. <MultiValueDict: {'files': [<InMemoryUploadedFile: example.txt (text/plain)>, <InMemoryUploadedFile: test.txt (text/plain)>]}> I want to list the urls in my html template but I cant seem to get them to show up. views.py def CreateNewPost(request,cluster_code): form = PostForm() if request.method == 'POST': form = PostForm(request.POST,request.FILES) if form.is_valid(): add_cluster_code_to_form = form.save(commit=False) add_cluster_code_to_form.cluster_code = Cluster.objects.get(cluster_code=cluster_code) add_cluster_code_to_form.save() return redirect('view-post',cluster_code) context = {'form':form} return render(request,'new-post.html',context) view-post.html {% extends 'base.html' %} {% block content %} {{cluster_code.cluster_code}} Test <a href="{% url 'new-post' cluster_code.cluster_code %}">Add New Post</a> {% for post in posts %} <hr> <p>{{ post.name }} {{ post.time }}</p> <p>{{ post.cluster_log | linebreaks }}</p> {% if post.files %} {% for file in post.file %} <p>{{ file.name }}</p> {% endfor %} {% endif %} {% endfor %} {% endblock content %} Any advice would be appreciated -
Django delete objects with no relations
I have been trying to find a function/sample code that would delete from table all objects with no relations to different objects (I use many-to-many relationship). Documentation and google were not helpful. Anyone can help? -
How to increase or decrease FloatField by 1000 with it's default button?
I have a FloatField in my models. The increase and decrease buttons on the right side of this area normally increase or decrease by 1 each. Is it possible to do this 1000 by 1000? How can I do that? models.py class Customer(models.Model): ... credit_limit = models.FloatField(default=0, null=True) ... forms.py class NewCustomerForm(forms.ModelForm): class Meta: model = Customer fields = ('customer_name', 'country', 'address', 'customer_number', 'phone_number', 'email_address', 'credit_limit', 'currency_choice') to be clear: -
How to assert in django pytest when matching query does not exists
How to assert in django pytest when matching query does not exists @pytest.mark.django_db def test_abc_pending_response(sent_xyz): #Test count is 1 rider_pending_response() sent_orders.refresh_from_db() #Test count is 0 or matching query does not exists assert XYZ.ObjectDoesNotExist #(This assert is not working) -
Why the reponse of my website is slow ? django heroku TTFB
First of all, thank you everyone for reading this post. I have a website performance issue at heroku with django. I hope to be able to find the enthusiastic help of the programmers in this group. I've been using django and heroku since March for a website with a small project of mine. The problem I have is that every time I call the website, the website responds quite slowly. I have researched and optimized the images. I also tested that my data connection at amazon s3 is pretty fast too. At the moment I don't understand why the website's green (TTFB) response time is quite slow. It seems to be the main cause of my slow website. Hope there is help or guidance for me to find out and fix this performance error. Thank you very much. My picture attached includes the docker file I use deploy for heroku, the packages I'm using and how I find out the delay. Thank you very much once again. -
How can I delete in one View OLD model OBJECT and create NEW with COPIED fields?Django
I have a model Book: models.py class Book(core.BaseModel): MAX_TAG_NUMBER = 99999 class Statuses(models.IntegerChoices): AVAILABLE = 1, 'Available' NOT_AVAILABLE = 2, 'Not Available' author = models.ForeignKey( Author, models.PROTECT, verbose_name='Author', related_name='author_name', ) tag_number = models.PositiveIntegerField('Tag number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) year = models.PositiveSmallIntegerField( 'Year', default=default_current_year, validators=[validate_current_year], ) status = models.PositiveSmallIntegerField('Status', choices=Statuses.choices, default=Statuses.AVAILABLE) I want to create button which delete object by id and copy all fields from this OLD object and CREATE new model object with this fields BUT deleted field 'tag_number' which I want to create again. I created this: class BookUpdateView(core.DeleteView): form_class = BookTagForm template_name = 'book/book_update.html' success_url = reverse_lazy('book:book-list') But I don't understand: 1)how to Delete all this fields in View and create new object with this copy of fields EXCLUDE tag_number? 2)Which view it must to be?CreateView, UpdateView? How can I delete and create in the same view class BookTagForm(core.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Book fields = ('tag_number', 'author', ) def save(self, commit=True): instance = super().save(commit=False) instance = Book.objects.create( author=self.cleaned_data['author'], status=self.cleaned_data['status'], tag_number=self.cleaned_data['tag_number'], year=self.cleaned_data['year'], ) if commit: instance.save() return instance -
How to upload multiple image django DRF from Flutter
I have models Car and CarImage and serializers: class Car(models.Model): title = models.CharField('title',max_length=200) def __str__(self): return self.title class CarImage(models.Model): car = models.ForeignKey(Car,on_delete=models.CASCADE,related_name='car_image',related_query_name='car_image') image = models.ImageField(upload_to='test_media/',null=True,blank=True,) def __str__(self): return f'{self.id} Image' class Car_Image_Serializer(serializers.ModelSerializer): class Meta: model = models.CarImage fields = ('id','image') class Car_Serializer(serializers.ModelSerializer): car_image = Car_Image_Serializer(many=True,required=False) class Meta: model = models.Car fields = ('title','car_image') def create(self, validated_data): if 'car_image' in validated_data: car_image= validated_data.pop('car_image') car_instance= models.Car.objects.create(**validated_data) for img in car_image: models.CarImage.objects.create(car=car_instance,image=img) return car_instance if 'car_image' not in validated_data: car_instance= models.Car.objects.create(**validated_data) return car_instance and in flutter I send images with library Dio: FormData formData1 = FormData.fromMap({ 'title': 'test', 'car_image': [ { 'car_image': await MultipartFile.fromFile( image_path, filename: fileName, ) } ] }); var response = await dio.post( url, data: formData1, ); and I get OrderedDict() { "title": "test", "car_image": [ { "id": 7, "image": "https://temike.pythonanywhere.com/media/OrderedDict()" } ] } -
device_detail() missing 1 required positional argument: 'pk'
im currently stuck on a error: device_detail() missing 1 required positional argument: 'pk' I cant seem to get past this error My codes: urls.py path('device/<int:pk>/', DeviceDetailView.as_view(), name='device-detail'), path('device/device_detail/', views.device_detail, name='device-detail'), views.py class DeviceDetailView(DetailView): model = Device template_name = 'interface/device_detail.html' def device_detail(request, pk): device = Device.objects.get(pk=pk) return render(request, 'interface/device_detail.html',{'devices':device}) -
Django - Is it possible to create a event/trigger based scheduler?
Normally what we do is a time-based scheduler, which may repeat after certain period of time. But for some reason, I want to create a trigger-based scheduler. If I have n rows in a table_1 then I need to create n scheduler. So I create another table (called table_2) that stores a scheduler name (randomly generated), for each new record in table_1. I receive real-time data from an API, now if some condition is matched by any of the rows in table_1, I need to trigger the scheduler from table_2 related to that row. I am little bit confuse how to trigger scheduler once all the condition is matched for the related row. Does anyone have any suggestions? Thanks -
Removing pycache files from Django project
Recently I have tried cloning my production code to a different pc. Then I have connected my project to a blank DB and run the command python manage.py makemigrations and after that, I can see that my migrations folder was updated with some pycache files. URL: /folder/app/migrations/pycache I know that the migrations files are very important but here the problem is the production DB contains data and the DB in that different PC is empty. I think if I push these pycache files to the production it might create conflict. My idea is not to push these pycache files(/folder/app/migrations/pycache) into my production environment and ignore them using the gitignore(as I am using git for version control). Am I doing the right thing? and Should/can I gitignore all the pycache files from the project. -
How to add a text editor and compiler in a django page
I am currently working on a project ,where I have to add a text editor and a compiler into my page.I have to also give a functionality, for the user to execute the code and display it on the html page. Here is an example page. https://www.w3schools.com/python/trypython.asp?filename=demo_compiler I want to create a page like this.Where do I start? (I have made a text area where the user can write python code.Then I execute that text file on the server with exec(code_from_textarea).But I found out this is dangerous.So I am stuck) -
How to delete image using image_id with image_id pass as a parameter in django rest framework
How to delete image using image_id with image_id pass as a parameter in django rest framework