Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to extract only day from timestamp in Django
I want to get a specific date like "8" out of (2021-8-3) but it's showing like this image how can I extract the specific date? usertime = User.objects.filter(groups__name = 'patient').values('date_joined').annotate(date_only=Cast('date_joined', DateField())) -
Whats the best websocket solution without too much overhead?
I'm fairly new to real-time databases with WebSockets so I'm facing probably the most important question when it comes to starting, which database and approach within the backend are the fastest and most reliable to set up and scale. I'm having a Django Backend with MongoDB (Djongo) and React in my frontend. Hosted on a google cloud linux VM. I'm currently comparing Websocket solutions for creating Components like text-editors that can be used collaboratively like google docs for example. To keep everything tidy I would have loved to go with an approach within Django but it seems so much overhead to work with Websockets in Django compared to other solutions. What I've gathered so far by trying all of these. Django: Has a lot over overhead as you need, Channels, Redis and therefore all the setup for it to use real-time WebSocket communication. Channels itself seemed kind of ok to set up but with an addition of Redis, the ASGI configs, and then making sure it works with my Mongo DB backend seems very complex to me in comparison to other systems with a lot of potential problems in the way. I coded everything and got most of it working … -
How can I save messages from my facebook webhook to a textfile using python and django. The code is attached below
if 'message' in message: # Print the message to the terminal print(message) # Assuming the sender only sends text. Non-text messages like stickers, audio, pictures # are sent as attachments and must be handled accordingly. print(message['message']['text']) respondinging = input("enter response") post_facebook_message(message['sender']['id'], respondinging) return HttpResponse() -
Integrating a javascript pipeline to Django
I am trying this tutorial to integrate a modern JavaScript pipeline into a Django application. Javascript code is supposed to write a "Hello webpack" into the page, but it does not. Since I already have an existing django project/app, I am writing on top of it. index-bundle.js is created with the content at the end of this post. django manage.py collect-static collects it. https://mysite/static/index-bundle.js loads the js file. There is no console error message. I see <script src="/static/index-bundle.js"></script> in the html generated, so everything should be fine. What is wrong here? index-bundle.js (comments deleted): /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./assets/index.js": /***/ (() => { eval("function component() {\r\n const element = document.createElement('div');\r\n element.innerHTML = 'Hello webpack';\r\n return element;\r\n}\r\n\r\ndocument.body.appendChild(component());\n\n//# sourceURL=webpack://project_dir/./assets/index.js?"); /***/ }) /******/ }); /******/ var __webpack_exports__ = {}; /******/ __webpack_modules__["./assets/index.js"](); /******/ /******/ })() ; -
how to set new unicode codepoints to my language in django settings to support
i'm trying to add my language (kurdish) which is not existing in languages list in django , but i dont know where to find unicode codepoints from django.conf import global_settings import django.conf.locale from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'ku' #ROSETTA_LANGUAGES = ( # ('en',_('english')), # ('ar',_('arabic')), # ('ku',_('kurdish')) #) LANGUAGES = ( ('en',_('english')), ('ar',_('arabic')), ('ku',_('kurdish')) ) ROSETTA_WSGI_AUTO_RELOAD = True EXTRA_LANG_INFO = { 'ku': { 'bidi': True, # right-to-left 'code': 'ku', 'name': 'Kurdish', 'name_local': u'\u0626\u06C7\u064A\u063A\u06C7\u0631 \u062A\u0649\u0644\u0649', # i have to change it to my language code LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI + ["ku","kurdish"] LOCALE_PATHS = ( os.path.join(BASE_DIR,'locale/'), ) 'name_local': u'\u0626\u06C7\u064A\u063A\u06C7\u0631 \u062A\u0649\u0644\u0649' used for another language(ughyry) and now it raise this error invalid token in plural form: EXPRESSION note kurdish use arabic character with a very little different -
How to pass variables in template to an ajax script? Django
I have a like button and I want ajax to send a get request with some variables I passed through the view, how do I do that? Every explanation online does this by adding a data-catid attribute however the information im passing is slightly sensetive and I would much rather it wouldn't be in the html code. my button: <button id='like-button' color = 'black', class='likebutton'> Like </button> ajax code <script type="text/javascript"> $('#likebutton').click(function(){ var article_id; var user_id; $.ajax( { type:"GET", url: "like", data:{ article_id: article_id, user_id: user_id }, success: function( data ) { $( '#like'+ id ).addClass('btn btn-success btn-lg'); } }) }); </script> How do I pass the user id and article id? They are both in the template. If there is anything I forgot to add, code or explanation please notify me -
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