Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i cannot migrate new rows to my table.It throws error with previous deleted tables ?how can i fix it?
[enter image description here][1] [1]: https://i.stack.imgur.com/0wUsP.png -
Do we need to use login() function when we authenticate user only with social auth in Django?
see the following code I use github for login the user. so, Do I need to put login() function when we use only social auth in django? def user_login(request): user = UserSocialAuth.objects.all() if request.user.is_authenticated: login(request, user) // this return redirect("home_post") else: return render(request, "registration/login.html") -
Django OperationalError "Lost connection to MySQL server at 'reading initial communication packet', system error: 0"
I'm on a mac connecting to a remote ubuntu server using ssh. MySQL is installed and running on the server, and my Django project is on it as well. I'm able to use mysql -u [username] -p to get into mysql, and I'm able to run the Django project on my local machine. When I run python manage.py runserver, this is my error traceback: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/root/djangoenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/root/djangoenv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/root/djangoenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/root/djangoenv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/root/djangoenv/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/root/djangoenv/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "/root/djangoenv/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/root/djangoenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/root/djangoenv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in … -
Django accessible from the local pc where Django stored, but not accessible from another local device
I'm building an application using React TSX for the front-end side and Django for the back-end side. So the application is working properly and it is accessible from my local PC by localhost:5000 because the application is stored on that PC, the React TSX app and the Django backend files. But whenever I try to access the application from other local devices, my Mobile or Tablet, I keep getting Network Error from the catch of axios. I have tried a lot of ways but I'm still not able to grant access from Django or React TSX. So any help will be great guys. Thanks. settings.py .......... .......... CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ["GET","POST"] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ] CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True .......... .......... -
Django sorting and determine the position of user
I am trying to determine the rank of participants in terms of total_votes. Below is the code that sorts all the participants in terms of total_votes and date_joined. I have added date_joined as well while sorting because if there are 5 participants with same total_votes then it will sort them in terms of date joined which means if two participants A and B have same votes but participant A joined the competition earlier then participant A will be in front of participant B. ranked_data =participants.objects.order_by('-total_votes', 'date_joined') Now how can i determine the rank of participant with participant id. I have the participants model as below: class participants(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) fullname = models.CharField(max_length =50) email = models.EmailField(max_length =50, default='') display_image = models.ImageField(upload_to=path_and_rename, max_length=500, help_text="Select display image") date_joined = models.DateTimeField(null=True, blank=True) dob = models.DateTimeField(null=True, blank=True) gender =models.CharField(max_length =10) total_votes = models.IntegerField(default=0) Can someone one suggest me to rank participants in appropriate way? -
How can I delete the answers (code in body)?
I am creating a Q&A website for practice, I created the answer and the question model and linked them together, however I can not access the template that I set for the deletion of the answer model, I created a DeleteView to delete the question. Here is the code: views.py: class Politics_post_details(DetailView): model = PoliticsPost context_object_name = 'politicsposts' pk_url_kwarg = 'qid' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # now you can get any additional information you want from other models question = get_object_or_404(PoliticsPost, pk=self.kwargs.get('qid')) context['answers'] = Answer.objects.filter(post=question).order_by('-date_posted') return context class AnswerDelete(UserPassesTestMixin,DetailView): model = Answer success_url = reverse_lazy('Lisk home') pk_url_kwarg = 'aid' def test_func(self): answer = self.get_object() if self.request.user ==answer.author: return True return False urls.py(not root): path('politicspost/<int:qid>/createanswer/',views.CreateAnswer.as_view(template_name='lisk_templates/createanswer.html'),name = 'Answer'), path('politicspost/<int:qid>/answer/<int:aid>/delete/',views.AnswerDelete.as_view(template_name = 'lisk_templates/answer_delete.html'),name='Answer_Delete'), path('politicspost/<int:qid>/',views.Politics_post_details.as_view(template_name='lisk_templates/politics_post_details.html') I created the template but whenever I try to access it, it gives me an error as follows: NoReverseMatch at /politicspost/29/ Reverse for 'Answer_Delete' with arguments '(36,)' not found. 1 pattern(s) tried: ['politicspost/(?P<qid>[0-9]+)/answer/(?P<aid>[0-9]+)/delete/$'] Thanks in advance. -
When I clicked on submit button nothing showed up in my database
I have a register form but when I click on submit button nothing show up in my database and when I created superuser that user was saved to database but if I register with the form it does nothing. forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class RegisterForm(UserCreationForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'password1', 'password2' ) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['first_name'].widget.attrs.update({'placeholder': 'First Name', 'id': 'first-name'}) self.fields['last_name'].widget.attrs.update({'placeholder': 'Last Name', 'id': 'last-name'}) self.fields['email'].widget.attrs.update({'placeholder': 'Email Address', 'id': 'email-address'}) self.fields['password1'].widget.attrs.update({'placeholder': 'New Password', 'id': 'password1'}) self.fields['password2'].widget.attrs.update({'placeholder': 'Re-enter New Password', 'id': 'password2'}) views.py # login and register function def loginAndRegister(request): # register form if request.method == 'POST': registerForm = RegisterForm(request.POST) if registerForm.is_valid(): registerForm.save() messages.success(request, 'Your account has created successfully! you can log in now') return redirect('login') else: registerForm = RegisterForm() context = {'registerForm': registerForm} return render(request, 'account/loginAndRegisterPage.html', context) html view <form method='POST'> {% csrf_token %} <li>{{ registerForm.first_name }}</li> <li>{{ registerForm.last_name }}</li> <li>{{ registerForm.email }}</li> <li>{{ registerForm.password1 }}</li> <li>{{ registerForm.password2 }}</li> <li><input type="submit" value="Create Account"></li> </form> -
how to set pagination in django custom APIView?
I have a very simple APIView, but I don't know how to setup pagination here. In this scenario I create a CustomPagination. pagination_class = CustomPagination works OK when I define queryset at the beginning in generics.ListAPIView, for ex. queryset = Event.objects.all() but not with custom get: views.py: class ProductAPIView(APIView): def get(self, request): pagination_class = CustomPagination data = Product.objects.filter(status=1) product_serializer = ProductSerializers(data,many=True) productData=[] for record in product_serializer.data: value = json.dumps(record) temp = json.loads(value) _id = temp['id'] title = temp['title'] sub_title = temp['sub_title'] productData.append({"id":_id, "title":title, "sub_title":sub_title}) return Response({"productData":productData}) pagination.py: from rest_framework.pagination import PageNumberPagination class CustomPagination(PageNumberPagination): page_size = 1 page_size_query_param = 'page_size' max_page_size = 1000 -
Django serializers get aggregated sum and count
serializers.py class BuildPlanNewSerializer(serializers.ModelSerializer): class Meta: model = BuildPlanNew fields = "__all__" class BuildPlanListNewSerializer(serializers.ModelSerializer): class Meta: model = BuildPlanListNew fields = "__all__" models.py class BuildPlanNew(models.Model): emp_id = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True) StartDate = models.DateTimeField() EndDate = models.DateTimeField() BuildPlanStatusID = models.ForeignKey(GlobalStatus, on_delete=models.CASCADE) class BuildPlanListNew(models.Model): BuildPlanID = models.ForeignKey(BuildPlanNew, on_delete=models.CASCADE, null=True, blank=True, related_name="build_plan_list_new") ProductID = models.ForeignKey(Product, on_delete=models.CASCADE) TotalPlanQty = models.IntegerField() TotalBuiltQty = models.IntegerField()) QtyPreset = models.IntegerField(default=None, max_length=256) Objective = models.IntegerField(default=None, max_length=256) QtyAssigned = models.IntegerField(default=None, max_length=256) view.py class BuildPlanNewView(viewsets.ModelViewSet): queryset = BuildPlanNew.objects.all() serializer_class = BuildPlanNewSerializer class BuildPlanListNewView(viewsets.ModelViewSet): queryset = BuildPlanListNew.objects.all() serializer_class = BuildPlanListNewSerializer Result i am getting: [{ "id": 6, "StatusName": "1234", "StartDate": "2020-07-26T12:00:00Z", "EndDate": "2020-08-01T12:00:00Z", "emp_id": 1, "BuildPlanStatusID": 25 }] Result i am expecting: [{ "id": 6, "StatusName": "1234", "build_plan_list_count": 5, "QtyPreset_count":20, "Objective_count":30 "StartDate": "2020-07-26T12:00:00Z", "EndDate": "2020-08-01T12:00:00Z", "emp_id": 1, "BuildPlanStatusID": 25 }] Here i wants to fetch aggregated sum and average from foreign key table. Need QtyPreset_count sum as QtyPreset_count Need Objective_count sum as as Objective_count I have shared my models views and serializers Please have a look -
Django - Where should signals be placed?
collection.models.py: class Collection(Model): items = ManyToManyField(Item) ... item.models.py class Item(Model): state = OneToOneField('ItemState') ... class ItemState(Model): item = ForeignKey('Item') ... Structure explanation: An item only has a single state at a time, but the client wants to track its state history. I want to write a signal that creates a new state when a Collection is created. Due to circular imports, I am separating my signals from my models. Now my question is do I write the signal for the above mentioned under collection_signals.py or item_state_signals.py. My guess is that both will work, but what would be the logical place to search for the above mentioned signal? I assumed collection since Collection is the sender, but then again this is about creating states and various models will be creating states (e.g. when a new item gets created that should trigger a new state as well) -
Download button security
I'm just wondering how secure my method is to have downloadable files. I have a model for uploading files and have <a> tag download button in my template served from a@login_required view. I just want to be sure there is no way for non-authenticated users to access the files. Also when I click the download button it just opens the file in a new tab. Why is that? Here's my code: models.py class File(models.Model): title = models.CharField(max_length=255) file = models.FileField(upload_to='dealer-admin/') class Meta: verbose_name_plural = "Files" def __str__(self): return self.title views.py @login_required def downloads_view(request): context = { 'files': File.objects.all(), } return render(request=request, template_name="dashboard/downloads.html", context=context) template {% for file in files %} <a href="{{file.file.url}}" download> <button class="download-button p-2" type="submit"><i class="material-icons pr-2">cloud_download</i>Download</button> </a> {% endfor %} -
How to display a selected post on a comments form
So I am working on a project in which a user can post a video and comment on other people's videos such like instagram. The comments page should have 3 parts, 1 a form that uploades a comment(which is done), and a form that displays the comments(which also works) and finally the video that user selected to comment on (which is not displaying). How can I make this video show up on the comments page? models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username)) class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank=True) user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') updated = models.DateTimeField(auto_now=True) created =models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) def get_absolute_url(self): return reverse('comments', args=[self.pk]) views.py def comments(request, pk): post = get_object_or_404(Post, pk=pk) comments = Comment.objects.filter(post=post) if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') comment = Comment.objects.create(post=post, user=request.user, content=content) comment.save() return HttpResponseRedirect(post.get_absolute_url()) else: comment_form = CommentForm() context2 = { "comments": comments, "comment_form": comment_form, } return render(request, 'comments.html', context2) comments.html <div class="post-container"> <video class="video" width='400'> <source src='{{ video.url }}' type='video/mp4'> </video> </div> <div class="comment-container"> <form method="post"> {% … -
How do I pass **kwargs when instantiating an object and access it in the class's __init__() method
Here I'd like to pass a **kwargs dictionary when instantiating my PlayerForm objects and be able to access it when calling __init__() method. This is what I've done below but it's not working. This is somewhere in my views.py file: context = {'player_form': PlayerForm(kwargs={'user': request.user})} This is in my forms.py file from .models import Game, Player class PlayerForm(forms.ModelForm): class Meta: model = Player fields = ['game', 'username'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if kwargs.get('user'): self.fields['game'].queryset = Game.objects.exclude(player__user=user) -
Pass object id from template to form on next template
I have a post detail page for coding challenges at url /codingchallenges/int:pk, and within this page is a button for users to make a submission. This button takes them to /submission/new which is a form for the submission model. How can I pass the post id of the coding challenge into the submission form? -
How to resolve Django IntegrityError NOT NULL Constraint Field?
I'm building an online judge in which I have a Question model and an Answer model. models.py from django.db import models from django.core.validators import FileExtensionValidator from django.urls import reverse class Question(models.Model): title = models.CharField(max_length=100) content = models.TextField() solution = models.FileField( validators=[FileExtensionValidator(allowed_extensions=['txt'])], upload_to= 'media') def __str__(self): return self.title def get_absolute_url(self): return reverse('coder:detail', kwargs={'pk': self.pk}) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) result = models.CharField(max_length=100,default = 'answer', null = True, blank = True) # result = models.FileField( null= True, blank=True, default = 'media/media/output.txt', # validators=[FileExtensionValidator(allowed_extensions=['txt'])], upload_to= 'media') def __str__(self): return f'{self.question.title} Answer' def get_absolute_url(self): return reverse('coder:detail', kwargs={'pk': self.pk}) views.py from django.shortcuts import get_object_or_404, render from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, DetailView, CreateView, UpdateView, RedirectView from django.db.models import Q from .models import Question, Answer class CoderListView(ListView): model = Question template_name = "coder/coder_list.html" context_object_name = 'question' class CoderDetailView(DetailView): model = Question template_name = "coder/coder_detail.html" class CoderCreateView(CreateView): model = Answer fields = ['result'] context_object_name = 'answer' success_url = reverse_lazy('coder:list') template_name = "coder/coder_form.html" def form_valid(self, form): return super().form_valid(form) What exactly am I doing wrong here? I was trying out FileField earlier but when I kept getting an error, I tried CharField after flushing the database to debug further but I … -
Django: render list of forms
I'm new to Django (and still learning python...) I'm having an issue with form rendering and I'm clearly doing something wrong.. I'm able to create few forms in form.py and able to have them render as I want (case1 in bellow core). But when I want to bundle all forms into a list, then I can't get the render to work. I thought this would be an issue with passing the form to html but I doubt that as the print of the variable form in view.py shows no string in case#2 (but does show proper html in case1). So I believe my issue is elsewhere? Help would be appreciated! >more form.py from django import forms class AppConfig(forms.Form): # case1 working: # myform1 = forms.CharField(required=False, initial="test1") # myform2 = forms.CharField(required=False, initial="test2") # case2 not working: myform = [ forms.CharField(required=False, initial="test1"), forms.CharField(required=False, initial="test2")] >more views.py from django.http import HttpResponse from django.shortcuts import render from django import forms def app_config_view(request, *args, **kwargs): form = AppConfig(None) print("form looks like:") print(form) return render(request, "app_config.html", {"form":form}) >more app_config.html {% extends 'base.html' %} {% block content %} <h1>APP config page</h1> <form method="post" action="."> {% csrf_token %} <input class="btn btn-primary" type="submit" value="Save" name="save"> <input class="btn btn-primary" type="submit" … -
Django cannot find images
I use Django ,everythings works perfectly fine but i cannot load images. My settings.py file STATIC_URL = '/static/' STATICFILES_DIR=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT=os.path.join(BASE_DIR,'assets') My html file <!DOCTYPE html> {% load static %}[enter image description here][1] <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>First App</title> </head> <body> <h1>Yeah..! this is index.html file</h1> <img src="{% static "images/pic1.jpg" %}" alt="Nothing to show"> </body> </html> -
inline YAML fixture for ManyToMany relation
I have two models with one containing a ManyToManyField relationship to the other and I know how to create separate YAML fixtures for them: - model: books.Author pk: 1 fields: name: Author One books: [1, 2] - model: books.Book pk: 1 fields: title: Book One release_date: 2010-01-01 00:00:00+00:00 author: 1 - model: books.Book pk: 2 fields: title: Book Two release_date: 2011-01-01 00:00:00+00:00 author: 1 But I want to populate these fixtures inline with natural keys so that I don't have to do as much bookkeeping with PKs. Something like this: - model: books.Author pk: 1 fields: name: Author One books: - model: books.Book pk: null fields: title: Book One release_date: 2010-01-01 00:00:00+00:00 author: 1 - model: books.Book pk: null fields: title: Book Two release_date: 2011-01-01 00:00:00+00:00 author: 1 Here's the corresponding models.py file: from django.db.models import Manager, Model, CharField, DateTimeField, ForeignKey, ManyToManyField, PROTECT from django.urls import reverse class Author(Model): name = CharField() books = ManyToManyField( to = 'Book', related_name = 'books') def natural_key(self): return (self.name) class BookManager(Manager): def get_by_natural_key(self, title, release_date, author): return self.get_or_create( title = title, release_date = release_date, author = author)[0] class Book(Model): title = CharField() release_date = DateTimeField() author = ForeignKey( to = 'Author', on_delete = PROTECT) … -
Django CreateView with pk from different unrelated model
I have a django CreateView where users can create new words. I also have an unrelated Song model, where users can choose to add words from the lyrics of the songs. So I've created a separate CreateView for this, so that I can have a different success url. The success url should go back to the song where the user was browsing. But I am struggling to figure out how to pass the pk of this particular object to the CreateView of a different model. This is my special CreateView: class CreateWordFromSong(LoginRequiredMixin, generic.CreateView): template_name = 'vocab/add_custom_initial.html' fields = ("target_word","source_word", etc.) model = models.Word from videos.models import Song def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super(CreateWordFromSong, self).form_valid(form) success_url = reverse_lazy('videos:song-vocab', kwargs={'pk': song_pk) #how to get song_pk? Everything works when I replace song_pk with the actual pk. I overwrite form_valid so that the user can be saved with the new object. Perhaps there is a way I can alter this so that I can also get the song_pk? I've played around with it a bit, but without luck. I get the song_pk from my url: path('song/<int:song_pk>/', views.CreateWordFromSong.as_view(), name='create-song'), So I should have access to it. But when I … -
Permission Error Loading Pretrained Model, Django, AWS
I'm working on deploying a Django app on AWS. Locally, everything works well. When deployed, the website opens fine, but when i try to run a deep learning model it gives me an Errno 13 Permission Error. /severity is the page of the website where this occured. Any and all help is appreciated :) Error Displayed on Site Request Method: POST Request URL: http://radiology-ai-env.eba-wgmpba4k.us-west-2.elasticbeanstalk.com/severity/ Django Version: 3.0.8 Python Version: 3.6.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tinymce', 'main'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/opt/python/current/app/main/views.py", line 62, in severity results = severity_model(image, mask) File "/opt/python/current/app/main/ml_models.py", line 11, in severity_model return Image_based_severity_prediction.run_model(image, mask) File "/opt/python/current/app/main/Image_based_severity_prediction.py", line 70, in run_model model_eff = EfficientNet.from_pretrained('efficientnet-b0') File "/opt/python/run/venv/local/lib/python3.6/site-packages/efficientnet_pytorch/model.py", line 211, in from_pretrained load_pretrained_weights(model, model_name, load_fc=(num_classes == 1000), advprop=advprop) File "/opt/python/run/venv/local/lib/python3.6/site-packages/efficientnet_pytorch/utils.py", line 327, in load_pretrained_weights state_dict = model_zoo.load_url(url_map_[model_name]) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/torch/hub.py", line 480, in load_state_dict_from_url os.makedirs(model_dir) File "/opt/python/run/venv/lib64/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/opt/python/run/venv/lib64/python3.6/os.py", … -
Want to show old and new data from user in single template in django
user gives me data I show it in html on same page now user gives me new data i want this new data and previous data both to be showed on the html like in chat but on website Can any one help me or guide me how to achieve it in django ? -
Get selected value in html select field for django
hey everyone i am doing a website for my university athletic, the thing is in my program i created a productbase and then models of this product, for stock control, and i have a problem here in my html of product, i created a select field in html to get the choice the model that someone want to buy, but i need to get the value of the select because is my model pk to put in the cart. <select> {% for produtos in produtobase.get_produto %} <option value="{{produtos.pk}}">{{produtos.name}}</option> {%endfor%} </select> i need to put in this code the button to make the add cart item view, in portuguese 'Adicionar_produto',this is the button: <a href="{% url 'Adicionar_produto' produtos.pk %}"><button class="btn-btn-primary">Adicionar ao Carrinho</button></a> in produtos.pk i need to send the value of the selected field in my html code, if someone can help-me please answear this question it would help me a lot -
How to change destination of objects in django
guys I want to change destination of objects, to be more precise i want to save new objects from 1 application to 2 with fill in 1 application form -
User Specific Profile Page with CRUD functionality in Django
I'm a Django newbie and for the last few weeks, I've followed some foundational tutorials on app creation with user login, logout, and authentication functionality. In each tutorial, the CRUD functionality is enabled across all users but the content is aggregated on the application homepage. For example, in the blog creation tutorial, you can register a user, login to the application, and generate a blog post, however, the blog post is rendered on the application homepage where any user can view that content. Can anyone point me towards a resource (docs or tutorial) that explains how to create an isolated content page for the user? Meaning, once the user registers, logs in and creates a blog post, it will only populate in the user's personal 'home' page and is not viewable (nor can it be edited) by the other users. Thank you. -
How to see all possible query sets of a model in django
I have two models like below in django class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(....) last_name = models.CharField(_(....) email = models.EmailField(...) class VcsToken(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) as you can see VcsToken is related to User, and a user can have many VcsToken, So how do I get all the VcsTokens of a User. Similarly I have many one to many relationships from user to other models, so How do I know their reference name? (I know its a set but how do I know the set name? ) Is there any way to list the query set names for a model.