Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use MultipleChoiceFilter in graphene-django?
I have an Django application with graphql endpoint. I need the ability to filter objects at once by several values of a certain field. I have the following graphene Scheme: class ChannelFilter(FilterSet): type = MultipleChoiceFilter(choices=Channel.TYPES) class Meta: model = Channel fields = ['type'] class ChannelNode(DjangoObjectType): class Meta: model = Channel filter_fields = ['type'] interfaces = (relay.Node,) class Query(graphene.ObjectType): channels = DjangoFilterConnectionField( ChannelNode, filterset_class=ChannelFilter ) schema = graphene.Schema(query=Query) Then i tried the following graphql queries to filter my objects: query { channels(type: "BOT") { edges { node { id } } } } As a result, the following error: { "errors": [ { "message": "['{\"type\": [{\"message\": \"Enter a list of values.\", \"code\": \"invalid_list\"}]}']", "locations": [ { "line": 2, "column": 3 } ], "path": [ "channels" ] } ], "data": { "channels": null } } query { channels(type: ["BOT"]) { edges { node { id } } } } As a result, the following error: { "errors": [ { "message": "Argument \"type\" has invalid value [\"BOT\"].\nExpected type \"String\", found [\"BOT\"].", "locations": [ { "line": 2, "column": 18 } ] } ] } How to use MultipleChoiceFilter correctly? Thanks -
django count instances in a model
I have a model ItemAdded and i made a signal so every time a user add an item to the cart an instance is created in the ItemAdded model so what i want to do is count the most added items (in an ascending order) , so what is the easiest way to do this ?? this is the model : class ItemAdded(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) # User instance instance.id content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # User, Product, Order, Cart, Address object_id = models.PositiveIntegerField() # , Product id, content_object = GenericForeignKey('content_type', 'object_id') # Product instance timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s added on %s" %(self.content_object, self.timestamp) class Meta: ordering = ['-timestamp'] # most recent saved show up first verbose_name = 'Object added' verbose_name_plural = 'Objects addded' -
Django giving error and Invalid Parameter to prefetch_related()
I know same questions are already asked but i am just unable to resolve my issue. I have 3 Models class CustomerPackage(models.Model): name = models.CharField(max_length= 20,blank=False, null=False) module = models.ForeignKey(Module, null=False, blank=False, on_delete=models.PROTECT) currency = models.ForeignKey(PackageCurrency,blank=False, null=False, on_delete=models.PROTECT, default=1) description = models.CharField(max_length= 500, blank=False, null=False) is_active = models.BooleanField(default=1) def __str__(self): return str(self.name) class UsecasePackage(models.Model): package = models.ForeignKey(CustomerPackage, null=False, blank=False, on_delete=models.PROTECT) use_case = models.ForeignKey(UseCase, default=1, null=False, blank=False, on_delete=models.PROTECT) month_price = models.IntegerField( null=False, blank=False) quarter_price = models.IntegerField(null=False, blank=False) annual_price = models.IntegerField( null=False, blank=False) def __str__(self): return str(self.package) class PackageCurrency(models.Model): name = models.CharField(max_length= 20,blank=False, null=False) def __str__(self): return str(self.name) I want to get the result by reverse joining CustomerPackage model with other i.e UsecasePackage. I tried to do that like CustomerPackage.objects.filter(module=id).prefetch_related('UsecasePackage_set') It gives me the error that Cannot find 'UsecasePackage_set' on CustomerPackage object, 'UsecasePackage_set' is an invalid parameter to prefetch_related() -
Not able to access a django app in a django project(both are in same directory)
So, I'm trying to create a django project with a django app which can upload and download files. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'uploadapp.apps.UploadappConfig' ] I'm tryind to write this but this is not working and I'm getting an error which says that no module named uploadapp exists. What could be the reason for this? -
Django migrate does not create any migrations on Elastic Beanstalk
As title says. Here is my .ebextestions/django.config (not included in .gitignore of course) container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate python3 manage.py migrate user_auth --noinput" leader_only: true 02_collectstatic: command: "source /var/app/venv/*/bin/activate python3 manage.py collectstatic --noinput" 03_createsu: command: "source /var/app/venv/*/bin/activate python3 manage.py createsu" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "myApp.settings" PYTHONPATH: "/var/app/venv/staging-LQM1lest/bin:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: "myApp.wsgi:application" aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static packages: yum: git: [] python3-devel: [] mariadb-devel: [] setting.py file # [...] if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } # [...] cfn-init-cmd.log file 2020-10-24 19:06:58,897 P9954 [INFO] ************************************************************ 2020-10-24 19:06:58,898 P9954 [INFO] ConfigSet Infra-EmbeddedPreBuild 2020-10-24 19:06:58,901 P9954 [INFO] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2020-10-24 19:06:58,901 P9954 [INFO] Config prebuild_0_myApp 2020-10-24 19:07:03,679 P10119 [INFO] ************************************************************ 2020-10-24 19:07:03,679 P10119 [INFO] ConfigSet Infra-EmbeddedPostBuild 2020-10-24 19:07:03,682 P10119 [INFO] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2020-10-24 19:07:03,682 P10119 [INFO] Config postbuild_0_myApp 2020-10-24 19:07:03,690 P10119 [INFO] ============================================================ 2020-10-24 19:07:03,690 P10119 [INFO] Test for Command 01_migrate <<== Test succeded 2020-10-24 19:07:03,694 P10119 [INFO] Completed successfully. 2020-10-24 19:07:03,694 P10119 [INFO] ============================================================ 2020-10-24 19:07:03,694 P10119 [INFO] Command 01_migrate 2020-10-24 19:07:03,697 P10119 [INFO] Completed successfully. <<== Migration completed 2020-10-24 19:07:03,704 P10119 [INFO] ============================================================ 2020-10-24 19:07:03,704 P10119 [INFO] Command 02_collectstatic 2020-10-24 19:07:03,708 P10119 [INFO] Completed successfully. 2020-10-24 19:07:03,715 P10119 [INFO] … -
Does Django Rest Framework provides ModelViewSet but for single object
In my application I need to perform CRUD operations on a specific object (for instance the current logged users). I'm attempting to achieve a ModelViewSet which will operate only on a given queryset (for instance, request.user). A ModelViewSet exposes the following endpoints [GET, POST, PATCH, etc...] thing/{id} Since the object is given, I don't need anymore to retrieve the object with a specific ID. So I need something similar to a ModelViewSet but without the ending {id} part [GET, POST, PATCH, etc...] thing In there an already implemeted class to do this? I need to perform CRUD operations. -
Fetching data in realtime from databases via python's gui and web applications
Could someone please explain me the ways that I can receive data from databases (for example sqlite3) in realtime/online. Need an app which would be similiar to chat but with saving all messages to a database and showing messages in a specific window only from database in realtime (may be with a few seconds delay not so important). The main principle of the application - is the global mailing of information between production departments. Each message contains important information like: message text, ip address, username and etc. Do I understand right that for the web-applications there is only one way is to make json-API and fetch data from there using AJAX call? This is my example how I've done it: django (sqlite3) -> rest_framework's serializer -> JS Ajax (5 seconds delay script). (I've already implemented it in work company). So is there any AJAX alternative and is it possible to realize it with another way? Second question is how to make same application via GUI? I googled several days to find a such kind of example but there are only examples with the next functionality: "press button -> make query to db -> receive data". I would like to hear … -
How to develop multi country website for domain specific country with location specifc ads
I have a classified ads web that is developed on the Django rest framework and React.js and I want to deploy it on the country-specific domain, for example, Canada .ca India .in, etc what strategy should I follow to make it easily manageable and each domain-specific web show location related ads. Thanks -
Seller deletes an item from their store. What should happen to a buyer's order history that includes this item?
In buyer's order history, I am saving seller's items that were purchased, as objects. If a particular item object is deleted by a seller, this item shows up as null in order history. Should I be saving item object's data as plaintext to avoid losing data? -
Foreign keys are saved as integer instead of the string attributes in django model. Why can't foreign key value be string?
Foreign keys are saved as integer instead of the string attributes in django model. Why not string? class CreateRoutine(models.Model): createRoutineID = models.AutoField(default = None, max_length=20, primary_key = True, verbose_name='createRoutine ID') dpt_code = models.ForeignKey('Department',default=None,on_delete=models.CASCADE, verbose_name='dpt_code', db_column="dpt_code") fac_shortName = models.ForeignKey('Faculty',default=None,on_delete=models.CASCADE, verbose_name='fac_shortName', db_column="fac_shortName") batch = models.ForeignKey('Batch',default=None,on_delete=models.CASCADE, verbose_name='batch', db_column="batch") section = models.ForeignKey('Batch',default=None,on_delete=models.CASCADE, related_name='section', verbose_name='section', db_column="section") roomCode = models.ForeignKey('Room',default=None,on_delete=models.CASCADE, verbose_name='roomCode', db_column="room") crs_title = models.ForeignKey('Course',default=None,on_delete=models.CASCADE, verbose_name='crs_title', db_column="crs_title") courseCode = models.ForeignKey('Course',default=None,on_delete=models.CASCADE, related_name='Code', verbose_name='courseCode', db_column="courseCode") day = models.ForeignKey('TimeSlot',default=None,on_delete=models.CASCADE,verbose_name='day', db_column="day") duration = models.ForeignKey('TimeSlot',default=None,on_delete=models.CASCADE,related_name='duration', verbose_name='duration', db_column="duration") class Meta: db_table = '"tbl_createRoutine"' verbose_name = "CreateRoutine" verbose_name_plural = "CreateRoutine" -
AttributeError at /profiles/user-profile/2/ 'int' object has no attribute '_meta'
Here I am using an api of notifications. here is the reference of that api link. I have follow the instructions given on the github read me file. But when i try to send an email by actor to recipient .it shows me the error 'int' object has no attribute '_meta'. The actor field and recipient both accept user_ids and I have put them manually. But still didn't work. profiles/Views.py class UserProfileFollowToggle(LoginRequiredMixin,View): login_url = '/accounts/login/' def post(self, request, *args, **kwargs): user_to_toggle_pk=kwargs.get('pk') username_to_toggle = request.POST.get("username") profile_, is_following = UserProfile.objects.toggle_follow(request.user, request.user.id, user_to_toggle_pk ,username_to_toggle) return redirect(f'/profiles/{username_to_toggle}') profiles/models.py class ProfileManager(models.Manager): def toggle_follow(self, request_user,user_id,user_to_toggle_pk, username_to_toggle): profile_ = UserProfile.objects.get(user__username__iexact=request_user.username) is_following = False follower = profile_.follower.filter(username__iexact=username_to_toggle).first() if follower: profile_.follower.remove(follower.id) notify.send(user_id, recipient=user_to_toggle_pk, verb='unfollow you') else: new_follower = User.objects.get(username__iexact=username_to_toggle) profile_.follower.add(new_follower.id) notify.send(user_id, recipient=user_to_toggle_pk, verb='follow you') is_following = True return profile_, is_following traceback: Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\AHMED\grapPub\grabpublic\profiles\views.py", line … -
How to create a login pop up model in django-rest-framework in user is not authenticated
Am having simple django blog with a like button on it, but i want to have a login pop up model if user is not authenticated ##MODEL class Song(models.Model): name = models.CharField(max_length=120) like = models.ManyToManyField(User, blank=True, related_name="like") ##Like Api View class SongLikeApiToggle(APIView): authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] def get(self, request, slug=None, format=None): obj = get_object_or_404(Song, slug=slug) updated = False liked = False if obj.like.filter(id=request.user.id).exists(): obj.like.remove(request.user.id) liked = False else: liked = True obj.like.add(request.user.id) updated = True data = { 'updated':updated, 'liked': liked } return Response(data) ### TEMPLATE WITH JQUERY I want to have a login popup model if user clicks the like button bellow <a data-href="{% url 'music:like' object.slug %}" class="like_btn" > Like button here </a> function update(btn, verb){ btn.html(verb); } $(".like_btn").click(function(e){ e.preventDefault() var this_ = $(this); var likeUrl = this_.attr("data-href"); $.ajax({ url:likeUrl, method: "GET", data: {}, success: function(data){ console.log(data); var newLikes; if (data.liked){ //add like update(this_, "<i class='fa fa-thumbs-up'></i>"); }else{ //remove like update(this_, "<i class='fa fa-thumbs-o-up'></i>"); } },error: function(error){ console.log(error); console.log("error") } }) } ) below is a Loin model i want to pop up if user is now authenticated <!-- Modal HTML --> <div id="myModal" class="modal fade"> <div class="modal-dialog modal-login"> <div class="modal-content"> <form action="/examples/actions/confirmation.php" method="post"> <div class="modal-header"> … -
html template show me empty page
when i try to run server th project th 1st pg which content a list of names after i check one of them its suppose to show me details for this name but actually its not work the pg was empty can you pleas tell me whr is my mistak thank u project urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('new2/', include('new2.urls')), ] app (new2) urls.py: from django.contrib import admin from django.urls import path,re_path from new2 import views urlpatterns = ( # path('admin/', admin.site.urls), path('', views.index, name='index'), re_path(r'(?P<task_id>[0-9]+)/$', views.details, name='details') ) views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Task from django.template import loader, RequestContext from django.template.response import TemplateResponse def index(request): list_task = Task.objects.all() template = loader.get_template('new2/index.html') RequestContext = { 'list_task': list_task } return HttpResponse(template.render(RequestContext,request)) def details(request, task_id): detail = Task.objects.get(pk=task_id) RequestContext = { 'detail' : detail } return render(request,'new2/details.html',RequestContext) models.py: from django.db import models class Task(models.Model): def __str__ (self): return self.Name_task Name_task = models.CharField(max_length=200) Age_task = models.CharField(max_length=200) details.html: {{Task.Name_task}}</br> {{Task.Age_task}} -
how to save the value in the database in django?
this is my models.py class Profile(models.Model): name=models.CharField(max_length=30) choices = ( ('C', 'C'), ('C++', 'C++'), ('Java', 'Java'), ('Python', 'Python'), ) intrest = models.CharField(max_length=6, choices=choices) this is my views.py if request.method=="POST": choice=request.POST['choice'] this choice has the value which i want to add to my database.how to add this choice in my database? -
Containerize Django Fullstack application with Reactjs frontend served as a django app with webpack and babel
I'm building a fullstack Django app with react js , webpack and babel. My django backend is serving my react frontend as an app via port 8000 with webpack bundling my reactjs. I want to be able to containerize my app so that i will have independent services that ie frontend as container, backend as a container and probably postgresql as a container. Now the major challenge i'm facing is how best can i separate these two main service frontend and backend considering that my Django backend is serving my frontend reactjs app via port 8000. I dont want to use create react app to serve my frontend at its own port 3000, i want to go the webpack and babel route, where i create a frontend app in Django that will host my react js app and its static files. Ultimately my folder structure looks something similar to this -django-app -fontend-app -src-react -components -actions -reducers App.js -static -templates index.html urls.py -another-app -django-app settings.py Dockerfile manage.py package.json webpack.config.js .babelrc Also consider a solution that will be able to make the application scalable ie, providing scaling functionality for the frontend app and backend app services repsectively. -
Django : This field is required on POST request
I'm trying to create a serializer which outputs the Report and also the User information. My task is accomplished by this serializer: class ReportSerializer(serializers.ModelSerializer): latitude = serializers.CharField() longitude = serializers.CharField() city = serializers.IntegerField() type = serializers.IntegerField() # We have created a field which returns a value from get_marker_icon_url marker_icon = serializers.SerializerMethodField('get_marker_icon_url') status_str = serializers.SerializerMethodField('convert_status_toStr') type_str = serializers.SerializerMethodField('convert_type_toStr') status_color = serializers.SerializerMethodField('get_status_color') likes = serializers.SerializerMethodField('random_likes') user = ReportUserSerializer() class Meta: model = Reports fields = [ 'user', 'id', 'type', 'city', 'latitude', 'longitude', 'likes', 'type_str', 'status_str', 'status_color', 'attached_message', 'marker_icon', 'attached_photo', 'date_created' ] ... With this code my serializer returns a response like this: [ { "user": { "id": 1, "username": "3nematix", "profile_pic": "http://192.168.0.29:8000/frontend/static/frontend/images/reports/user_profile_pic.jpg", "verified": false }, "id": 1, "type": 9, "city": 0, "latitude": "6.5123333", "longitude": "51.512586", "likes": 27, "type_str": "OTHER", "status_str": "PENDING", "status_color": "orange", "attached_message": "test", "marker_icon": "OTHER", "attached_photo": "http://192.168.0.29:8000/frontend/static/frontend/images/reports/user_profile_pic_VRjIYTs.jpg", "date_created": "2020-10-21T23:19:06.899302Z" }, ...... ] And this is exactly what I need, but the problem is that when I'm trying to create a new object by a POST request, I get this response: { "user": [ "This field is required." ] } If I would remove 'user' from Meta and user = ReportUserSerializer() from the ReportSerializer class, then I can create a new … -
Filtering form fields
Is it possible to filter the values in the form, exactly what I mean is that only the names of tournament groups created for a given tournament are displayed in the form window and not, as in the present case, that all. this is my models.py file class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) user_group = models.ForeignKey(TournamentGroup, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) def __str__(self): return self.tournament_name class TournamentGroup(models.Model): group_name = models.CharField(max_length=256, null=True) tournament_name = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) def __str__(self): return self.group_name my forms.py file class TournamentUsersForm(forms.ModelForm): user_first_name = forms.CharField(required=True) user_last_name = forms.CharField(required=True) class Meta: model = TournamentUsers fields = ['user_last_name', 'user_first_name', 'user_tournament', 'user_group'] my views.py file def content(request, pk): tournament = get_object_or_404(Tournament, pk=pk) tournament_groups = TournamentGroup.objects.filter(tournament_name=tournament) users = TournamentUsers.objects.filter(user_tournament=tournament) form = TournamentUsersForm() if request.method == "POST": form = TournamentUsersForm(request.POST) if form.is_valid(): form.save() form = TournamentUsersForm() return render(request, 'ksm_app2/content.html', {'tournament': tournament, 'users': users, 'form': form, 'tournament_groups': tournament_groups}) all I wants is for the user to be able to choose only the team assigned to a given tournament -
Django media image not found when there is a trailing slash at the end
I added users avatar today and applied it for my current 15 users or so when i was migrating, i just found out that the path wan't specified correctly so I had a look at my admin page to see what went wrong. The wrong avatar url which all users currently have: ...DefUser.png/ The correct one: ...DefUser.png With the trailing slash it gives error, without gives the correct image. Is there anyway to fix that?! If not then How can i change the avatar image of all the current existing -15- users and make them all point to the same image? The code models.py class User(AbstractUser): ... avatar = models.ImageField( upload_to='users/img/avatar/', default="users/img/avatar/DefUser.png/") settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' AUTH_USER_MODEL = 'users.User' LOGIN_URL = '/signup/' urls.py: from django.conf.urls.static import static from django.conf import settings from django.urls import path, include ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
what does the plus sign mean in return redirect('/details/+product_id')
just need a brief expalanation , i stumbled over this randomly in a Django example, but couldn't find explanation def contact(request): if request.method == 'POST': product_id = request.POST['product_id'] product= request.POST['prodcut'] name = request.POST['name'] email = request.POST['email'] if request.user.is_authenticated: user_id = request.user.id has_contacted = Contact.objects.all().filter(prodcut_id=product_id, user_id=user_id) return redirect('/details/+product_id') i'm just lookin for the signification of using "+" in the redirect, if someone know Thank you very much -
Passwordless user registration in Django
How can I customize Django's default user model to password less authentication similar to Whatsapp? Only (use mobile number and OTP to verify) -
Elastic Beanstack Deployment w/ Django Docker Postgresql
AWS Elastic Beanstalk has an option to deploy Django apps, I don't want to use this option because I want to have the flexibility of using Docker. So I am choosing to deploy my Django app through the elastic beanstalk Docker platform instead. However, there isn't much documentation on how to configure a Django app with Docker for AWS EB and I cant find an example on github. My question is: What do I need to configure in my Dockerized Django app to run on AWS EB ? NGINX, Gunicorn, or both ? Is there an example of this somewhere I could look at. -
Django - How to trigger signals on multi type user create with one AbstractUser model
So I had this custom user model on my project. I want the user can register as a Profile and Client. I created two different models extended from my custom User model. The problem is, every time I sign-up from the client form, it also saved to the Profile model, And the opposite. Let say on my accounts app: # model.py class User(AbstractUser): username = models.CharField(max_length=100, unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=20) gender = models.CharField(choices=GENDER, max_length=10) class Meta: db_table = 'auth_user' def __str__(self): return self.username class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... email = models.CharField(blank=False, null=False, max_length=100) phone = models.CharField(blank=True, null=True, max_length=14) class Meta: verbose_name = 'Influencer Profile' def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) And then inside my client app: # model.py from accounts.models import User class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... company_name = models.CharField(max_length=50, unique=True) class Meta: verbose_name = 'Client Profile' def __str__(self): return f'{self.username} Client Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) And my signals.py looks like: accounts/signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() And one more signals on my clients app: @receiver(post_save, sender=User) … -
django display category name
I want to display the category name of a product when I enter it, how can I do this? How can I get the category name of each product? my model : class Category(MPTTModel): parent = TreeForeignKey('self', models.CASCADE, related_name='children') sub = models.BooleanField(default=False) name = models.CharField(max_length=300, ) ... class Product(models.Model): category = models.ManyToManyField(Category, related_name='category_product') .... my view : def test(request, id): products = get_object_or_404(Product, id=id) return render(request, 'home/new.html', {'products': products }) my template: <div class="card"> <h2>{{ products.name }}</h2><br><br> <p>{{ products.price}}</p><br> <p>{{ products.discount }}</p><br> </div> -
How to get primary key from template in django?
Here I am trying to get user_to_toggle id but that is coming none and i guess this is because i am doing something wrong. I am confuse that how can i get user_to_toggle id. I am getting his username but i want user id too. Here is my code. views,pyy class UserProfileFollowToggle(LoginRequiredMixin,View): login_url = '/accounts/login/' def post(self, request, *args, **kwargs): user_pk_to_toggle=kwargs.get('pk') #this is returning None. username_to_toggle = request.POST.get("username")#this is returning me username of toggle user. profile_, is_following = UserProfile.objects.toggle_follow(request.user, request.user.id ,username_to_toggle) return redirect(f'/profiles/{username_to_toggle}') follow_to_toggle.html <form class='form' method='POST' action="{% url 'profiles:toggle'%}"> {% csrf_token %} <input type='hidden' name='username' value="{% if username %}{{ username }}{% else %}hello{% endif %}"> <button class='btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}'>{% if is_following %}Unfollow {% else %}Follow{% endif %}</button> </form> if more code is required than tell me i will update my question with that information. -
Only one of the two model forms work, the second one is not working properly
I have two model forms in the same view relating to the same object model. They have different objectives, that's why I keep them separate. However, the first one changes the transaction_type attribute after saving, the other one does not. If I change the order and put the fasttransactionform first, it will change the transaction_type but then the fastcollectionform will not change the transaction_type. I appreciate your help, thanks in advance. views.py fastcollectionform = CollectionModelFormFast(request.POST) if fastcollectionform.is_valid(): transaction = fastcollectionform.save(commit=False) transaction.transaction_type = "Tahsilat" transaction.save() return redirect(request.path) fasttransactionform = TransactionModelFormFast(request.POST) if fasttransactionform.is_valid(): transaction = fasttransactionform.save(commit=False) transaction.transaction_type = "Harcama" transaction.save() return redirect(request.path)