Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models adding member to a project
Trying to figure out how to create a Project class for an app I am making. I am bringing inn a Profile from another app, containing username, names and avatar. Then i need a project name and i want to be able to bring inn members, to the specific project, but don't know how to go forward with that. models.py from django.db.models.deletion import CASCADE from django.db import models from profiles.models import Profile class Projects(models.Model): user = models.ForeignKey(Profile, on_delete=CASCADE) project_name = models.CharField(max_length=55, null=True, blank=True) members = how to get members inn this? Will add tasks, notes and a chat as seperate classes then bring them inn to the project as foreignkey, think that would be correct. But how to deal with the members and get them added to the project? -
Not Found The requested resource was not found on this server
I follow this address and I set DEBUG = False in appartement/settings.py in my project. I changed /etc/apache2/sites-available/000-default.conf: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /media /var/www/b9/appartement/cdn/cdn_medias Alias /static /var/www/b9/appartement/cdn/cdn_assets <Directory /var/www/b9/appartement/cdn/cdn_medias/> Require all granted </Directory> <Directory /var/www/b9/appartement/cdn/cdn_assets/> Require all granted </Directory> <Directory /var/www/b9/appartement/appartement> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess appartement python-path=/var/www/b9/appartement:/var/www/b9/django-virtualenv_b9/lib/python3.8/site-packages WSGIProcessGroup appartement WSGIScriptAlias /appartement /var/www/b9/appartement/appartement/wsgi.py </VirtualHost> but when i run django project, i got Not Found error about statics files and it can not found CSS files -
If any are null, do something
I have a view that performs some basic calculations, but sometimes not all fields have values added, so the calculations fail due to trying to do calculations that do exist. Is there a way to say if any fields contain null or blank then pass or do i need to write a if for every one? if QuestionnaireResponse.objects.filter(project_name_id=project_id, questionnaire_id=1).exists(): dist_resp = QuestionnaireResponse.objects.get(project_name_id=project_id, questionnaire_id=1) artist_percent = QuestionnaireAnswer.objects.get(question_id=3,response=dist_resp) marketing_percent = QuestionnaireAnswer.objects.get(question_id=4,response=dist_resp) advisers_percent = QuestionnaireAnswer.objects.get(question_id=5,response=dist_resp) community_percent = QuestionnaireAnswer.objects.get(question_id=6,response=dist_resp) team_percent = QuestionnaireAnswer.objects.get(question_id=7,response=dist_resp) partners_percent = QuestionnaireAnswer.objects.get(question_id=8,response=dist_resp) reserve_percent = QuestionnaireAnswer.objects.get(question_id=9,response=dist_resp) artist_percent_allocation = ((project.project_total_supply / 100)*(artist_percent.answer)) marketing_percent_allocation = ((project.project_total_supply / 100)*(marketing_percent.answer)) advisers_percent_allocation = ((project.project_total_supply / 100)*(advisers_percent.answer)) community_percent_allocation = ((project.project_total_supply / 100)*(community_percent.answer)) team_percent_allocation = ((project.project_total_supply / 100)*(team_percent.answer)) partners_percent_allocation = ((project.project_total_supply / 100)*(partners_percent.answer)) reserve_percent_allocation = ((project.project_total_supply / 100)*(reserve_percent.answer)) I have set a if on the first line which works, but sometimes that if can return true, but the lines below could be null. marketing_percent_allocation = ((project.project_total_supply / 100)*(marketing_percent.answer)) advisers_percent_allocation = ((project.project_total_supply / 100)*(advisers_percent.answer)) community_percent_allocation = ((project.project_total_supply / 100)*(community_percent.answer)) team_percent_allocation = ((project.project_total_supply / 100)*(team_percent.answer)) partners_percent_allocation = ((project.project_total_supply / 100)*(partners_percent.answer)) reserve_percent_allocation = ((project.project_total_supply / 100)*(reserve_percent.answer))` Is this possible? Thanks -
Can't connect MPTT with django.parler
I do e-commerce in django. I have Category model that I want to work with both django.parler and django-MPTT, because I want to make subcategories for category. I've done everything like in django-parler documentation to connect these two packages the right way. After saving the model, the following error appears: ImproperlyConfigured at /pl/admin/store/category/ TreeQuerySet class does not inherit from TranslatableQuerySet And I'm not sure why. My Category model: models.py class Category(MPTTModel, TranslatableModel): parent = TreeForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=200, db_index=True, unique=True, blank=True, null=True, default='') translations = TranslatedFields( name=models.CharField(max_length=200, db_index=True, blank=True, null=True, default=''), ) class Meta: unique_together = ['slug', 'parent'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def get_absolute_url(self): return reverse('store:product_list_by_category', args=[self.slug]) admin.py @admin.register(Category) class CategoryAdmin(TranslatableAdmin, MPTTModelAdmin): list_display = ['name', 'slug', 'parent'] search_fields = ['name'] def get_populated_fields(self, request, obj=None): return {'slug': ('name',)} -
ForigenKey in django preselected when creating a modelform for a a relation table
I want to have the Forgienkey to be preselected of it's relation table id, in example i want to create a job for a specific component with the component being already chosen. my view.py : def create_job(request, pk): component = Component.objects.all() component_id = Component.objects.get(id=pk) obj = Job.objects.get() obj.component_id(id=pk) instance = JobModelForm(instance=obj) form = JobModelForm() if request.method == 'POST': form = JobModelForm(request.POST,) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) context = { 'components': component, 'component_id': component_id, "form": form, "instance":instance, } return render(request, 'create_job.html', context) the form template : <form method='POST' action=''> {% csrf_token %} <span class="component-label-text">Job name</span> {% render_field form.name class="component-form-data-inputs" %} <span class="component-label-text">Job description</span> {% render_field form.description class="component-form-data-inputs" %} <span class="component-label-text">Job type</span> {% render_field form.type class="component-form-data-inputs" %} <span class="component-label-text">Check if Job is critical</span> {% render_field form.is_critical %} <br> <span class="component-label-text">Job interval</span> {% render_field form.interval class="component-form-data-inputs" %} <span class="component-label-text">Job Due date</span> {% render_field form.due_date %} <br> {% render_field instance.component class="component-form-data-inputs" %} <input type="submit" class="button1" value='Create Job' /> </form> -
Django Allauth: Duplicate Key Value Violates Unique Constraint: Key (username)=() already exists
I have been troubleshooting an issue with my custom allauth Django user model for some time. I only want to use email, first name, last name, and password as part of my user signup form, and I can get it to work once, but when a second user signs up, it says that the username already exists. I have seen others with a similar issue, but unfortunately their solutions do not work. If I remove the custom account form, then it does, but I need to include first name and last name in my signup form, so not sure how to work around that. Any help is appreciated! settings.py AUTH_USER_MODEL = 'accounts.CustomUser' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None # I have also tried ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' and 'email' ACCOUNT_FORMS = { 'signup': 'accounts.forms.CustomUserCreationForm' } models.py class CustomUser(AbstractUser): email = models.EmailField(max_length=256) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'first_name', 'last_name') -
How to get instance from global id in Django with Graphene Relay
graphql_relay has a function from_global_id which returns the model_name and the instance_id. However, it seems that to retrieve the model from the name of the model, we need to know in which app the model is, such as answers in the question asking how to get the model from its name. Is there a way to know the name of the app from the global id? Or is there any other way to retrieve the instance? -
Django and stripe handle successful payment
I am trying to handle successful payment using stripe webhook, in my stripe dashboard I see that the events are triggered and the payment_intent is successful but the order is not created views.py : from django.shortcuts import render from django.http import JsonResponse from django.http import HttpResponse import stripe import json from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from article.models import Order endpoint_secret = '1wwww' @require_POST @csrf_exempt def my_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None # Try to validate and create a local instance of the event try: event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'payment_intent.succeeded': checkout_session = event['data']['object'] # Make sure is already paid and not delayed _handle_successful_payment(checkout_session) # Passed signature verification return HttpResponse(status=200) def _handle_successful_payment(checkout_session): payed_order = Order.objects.create(order_id='test22') return payed_order -
Django - Could not parse the remainder: '++_RS' from 'annovar.GERP++_RS'
I have a JSON value that comes directly from a DB that has this label GERP++_RS This is part of a big dictionary and I need to display the correspondent value on a HTML page, but Django gives me this error Could not parse the remainder: '++_RS' from 'annovar.GERP++_RS' What would be best strategy to retrieve the value from this key? Would I need to process it before it gets to the template? Thanks in advance -
how to run django in pycharm in https
I need to run a python Django project with Pycharm IDE locally in HTTPS so that other services can talk with my service without any errors. I don't manage to run it locally in HTTPS -
Passing and using the request object in django forms
I'm trying to user the request object to create a dynamic dropdown list in my form using the following code: view: form = TransactionForm(request.user) form: class TransactionForm(forms.Form, request.user): # Payment methods get_mm_details = MMDetails.objects.filter(username=request.user) get_card_details = CardDetails.objects.filter(username=request.user) payment_meth = [] # form fields trans_amount = forms.IntegerField(label="Amount", min_value=0) payment_method = forms.CharField( label='Payment method', widget=forms.Select( choices=payment_meth ) ) is there a way of using the request object in a form? -
Django --- how to get pdf model upfront in a html download button?
I would like to create a HTML button where it loads the pdf file from the database. Do you know how to create the button to upload the latest pdf file from the model? Below is my code so far from the model: class PdfLoad(models.Model): file = models.FileField(upload_to='Portfolios/') Code for admin.py: admin.site.register(PdfLoad) Code HTML code: <!-- Download link --> <section class="about section" id="CV"> <h2 class="section-title">Curriculum Vitae</h2> <div class="d-flex justify-content-center"> <a href ="{{pdf.file}}"><button type="submit" class="cv__button" onclick="blank">CV</button></a> </div> </section> do I have to do something for the setting.py file ?? -
Filter Dataset Based on Account Log In
I'm trying to filter the dataset shown in my table based on the user that logged in within the previous page. My app is set up in a way that it's a simple log-in screen where you put a username and password, and then there's a single dataset feeding two screens: 1 = Week, 2 = Picks. On the first screen, you select which week you'd like to select picks for, and once you click into a week you can change your picks. When I've built apps in different solutions, my idea was to store username or week as a variable and then filter the dataset to just records pertaining to that criteria, but I'm not sure how to do that in Django. Thoughts? I have the following code: views.py class PickList(LoginRequiredMixin, CoreListView): model = Pick def user_picks(request): Pick.objects.filter(submitter={{ request.user.get_full_name|default:request.user }}) return render(request, 'app/pick_list.html', {'Pick': Pick}) app urls.py urlpatterns = [ path('', home, name='home'), path('picks/', PickList.as_view(), name='pick-list'), path('pick/<int:pk>/', PickDetail.as_view(), name='pick-detail'), path('picks/<str:submitter>', user_picks(), name='pick-list'), path('weeks/', WeekList.as_view(), name='week-list'), path('weeks/<int:pk>/', WeekDetail.as_view(), name='week-detail'), ] account urls.py urlpatterns = [ path('login/', views.LoginView.as_view(template_name='account/signin.html', authentication_form=AuthenticationForm, extra_context={ 'title': 'Login', 'extra_title': 'Please sign in', }), name='login'), path('logout/', views.LogoutView.as_view(next_page='account:login'), name='logout'), ] models.py class Pick(models.Model): submitter = models.CharField(max_length=50, verbose_name='Submitter', null=True, blank=True) … -
Custom User return empty get_all_permissions()
I'm just trying start work with Permissions to learn how thats work. In shell i have empty set() result. I see this question, is the same of that, but i can't find what is missing im my code: I creared Custom User from AbstractBaseUser, so my model is like: settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ] AUTH_USER_MODEL = 'users.User' AUTHENTICATION_BACKENDS = [ 'users.backends.CustomModelBackend', ] models.py class UserManager(BaseUserManager): def create_user(self, email, username, phone, password = None): ... def create_superuser(self, email, username, phone, password = None): ... class User(AbstractBaseUser, PermissionsMixin): ... objects = UserManager() ... def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True backends.py class CustomModelBackend(backends.ModelBackend): def user_can_authenticate(self, user): return True In shell i try something like: >>> from users.models import User >>> user_test = User.objects.get(email="user@example.com") >>> user_test.get_all_permissions() set() That user is superuser. What is needed to check that permissions? -
Filter for several items of the same field Django
I have a view like this: class ProductViewSet(viewsets.ModelViewSet): ... filter_class = ProductFilter and ProductFilter: class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = ['brand'] the problem is that when I send a GET /products/?brand=Adidas+Nike, I get an error [ "Select a valid choice. Nike Adidas is not one of the available choices." ] How can I fix it that it will filter for several items of the same field. -
django filter a prefetch_related queryset
I am trying to use prefetch_related with a model with foreign key because I then need to query the database within a loop. models.py class SelfEvaluatedStatement(models.Model): evaluation_statement = models.ForeignKey(EvaluationStatement, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default=0) views.py queryset = SelfEvaluatedStatement.objects.prefetch_related( 'evaluation_statement__sku__topic__subject', 'evaluation_statement__sku__level' ).filter( evaluation_statement__sku__topic__subject=subject, evaluation_statement__sku__level=level ) for student_user in student_users: red_count = queryset.filter(user=student_user, rating=1).count() However, this hits the database with a new query each time I iterate through the loop. Is it possible to filter a queryset which has been prefetched, or am I thinking about this incorrectly? -
Getting and Resuming from Process ID in Python 3
I am developing a testapp in django for internal computing usage. I am using Octave (open source version of Matlab). The idea is to give the user a web interface, where user will type commands, and the commands will go to backend, get executed in octave, and return the results. And the key is to remember the values of all variables that the user has set previously without any recourse to database as octave does it automatically. The problem I am facing is that once I return from backend, I loose the parameter values. In essence, I create a shell process in django view using import subprocess; subprocess.run('a=2'). I capture the output and send it back to UI. And lets say user sends another command subprocess.run('a = a + 2'). But this time when I try to execute in backend, I am going to get error, because the value of parameter a is lost!! To make matters worse multiple users can access this app at the same time with their own set of data and operations. Now my question how can I get process ID of shell created using python, and resume later on using the same process ID and … -
Ajax url with parameter. The current path didn’t match any of these
I'm new in django. I try to delete element from database by ajax call. My ajax call send url with parameter which is pk of element to delete. Url looks fine but browser raise error that url pattern doesn't match to any of urlpatterns in my url.py. I have done similar project before and everything workerd good so I'm confused why it does't work now. Any Idea? urls.py: urlpatterns = [ path('', views.home,name='home'), path('mojerec',views.mojeRec,name='mojerec'), path('dodajrec',views.dodajRec,name='dodajrec'), path('receptura/(<int:receptura_id>)',views.receptura,name='receptura'), path('formJson/<str:skl>/', views.formJson, name='formJson'), path('receptura/formJson/<str:skl>/', views.formJson, name='formJson'), path('receptura/dodajskl/<str:sklId>/', views.dodajsklJson, name='dodajsklJson'), path('receptura/aktualizujTabela/<str:sklId>/', views.aktualizujTabela, name='aktualizujTabela'), path('receptuta/delSkl/<int:id>/', views.delSkl, name='delSkl'), ] views.py def delSkl (request,id): deletedElement=Skladnik.objects.filter(pk=id) response=serializers.serialize("python", deletedElement) deletedElement.delete() print('response', response) sys.stdout.flush() return JsonResponse({'response':response}) myjs.js function usuwanieSkladnika (pk){ $.ajax({ type: 'GET', url: `delSkl/${ pk }/`, success : function(response){console.log('sukces ajaxa z del'); cardBox.innerHTML='' tabelaDocelowa.innerHTML=''; updateTable() },//koniec sukcesa error : function (error){console.log('brak sukcesu ajaxa z del')}, }) } log: Page not found (404) Request Method: GET Request URL: http://localhost:8000/receptura/delSkl/13/ Using the URLconf defined in recipe.urls, Django tried these URL patterns, in this order: admin/ [name='home'] mojerec [name='mojerec'] dodajrec [name='dodajrec'] receptura/(<int:receptura_id>) [name='receptura'] formJson/<str:skl>/ [name='formJson'] receptura/formJson/<str:skl>/ [name='formJson'] receptura/dodajskl/<str:sklId>/ [name='dodajsklJson'] receptura/aktualizujTabela/<str:sklId>/ [name='aktualizujTabela'] receptuta/delSkl/<int:id>/ [name='delSkl'] users/ The current path, receptura/delSkl/13/, didn’t match any of these. -
Django - i have add onclick function into html and whenever i click into different button then it will render the same data. how to fix that?
<div class="home-food-row"> {% if allmenu %} {% for menu in allmenu %} <div class="home-food-menu-col"> <div class="filterDiv breakfast"> <div class="img-price-tag"> <div class="price-tag" id="price">{{menu.price}} only</div> <img class="home-page-food-img" src="{{menu.food_img.url}}" alt="Food" width="100%"/> </div> <h1 id="foodName_1">{{menu.food_name}}</h1> <p>{{menu.food_description}}</p> <button id="order" onclick="myFunction()">Place Order</button> </div> </div> {% endfor %} {% else %} <div class="col-md-12"> <p>No Food</p> </div> {% endif %} </div> /////////////////////////// JS Code //////////////////////////// function myFunction() { var price = document.getElementById("price"); var food = document.getElementById("foodName_1"); console.log(food); console.log(price); } enter image description here enter image description here -
how to get attribute from other model in your django template
SO I have these two models, One is Members other is PaymentDetail. What I want is all the members from Member model in my template which I can get from Members.object.all() but also I want the payment_status of all those members in my template next to them. I dont know how to do it as payment_status is not in the Member model. class Members(models.Model ): user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE) com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name') mem_status = models.CharField( max_length=20,choices=MEMBER_STATUS, verbose_name='Member Status') mem_note = models.TextField(null=True, blank=True) class PaymentDetails(models.Model): mem = models.ForeignKey(Members,on_delete=models.CASCADE, related_name="payment_details",verbose_name='Memeber Phone no') com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name') payment_month = models.DateField(default=datetime.now()) payment_amount_debit = models.IntegerField(null=True,blank=True) payment_amount_credit = models.IntegerField(null=True,blank=True) payment_status = models.CharField(max_length=16, choices=PAYMENT_DETAILS_CHOICES, default="1") payment_proof = models.ImageField(upload_to='images/') payment_note = models.TextField(null=True,blank=True) I searched alot and Found out there is somehting called related name and setname, but I am kinda new so I am not getting the desired results by using them too. -
Using data from the select tag to make queries based on the given id
I'm trying to make queries or to filter data based on the given id from the select tag that I have in the html. In the index.html I have the following: <div class="row"> <label for="patientId">Choose a patient:</label> <select name="patient" id="patient"> {% for item in patientId %} <option value="{{item}}"> {{item}} </option> {% endfor %} </select> In this select I have all the ids from the database, in the same page, I also have a chart that should display data based only on this id from the select tag. For this, I have the data declared in a script tag: var ctx = document.getElementById("weeklyChart"); var myLineChart = new Chart(ctx, { type: 'line', data: { labels: {{ hourArray|safe}}, datasets: [{ label: "Value", lineTension: 0.3, backgroundColor: "rgba(78, 115, 223, 0.05)", borderColor: "rgba(78, 115, 223, 1)", pointRadius: 3, pointBackgroundColor: "rgba(78, 115, 223, 1)", pointBorderColor: "rgba(78, 115, 223, 1)", pointHoverRadius: 3, pointHoverBackgroundColor: "rgba(78, 115, 223, 1)", pointHoverBorderColor: "rgba(78, 115, 223, 1)", pointHitRadius: 10, pointBorderWidth: 2, data: {{ glucoseArray|safe}}, }], }, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", titleMarginBottom: 10, titleFontColor: '#6e707e', titleFontSize: 14, borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, yPadding: 15, displayColors: false, intersect: false, mode: 'index', caretPadding: 10, callbacks: { label: function(tooltipItem, chart) { var datasetLabel … -
Drag and Drop sorting with django and ajax
I want to add drag and drop functionality to the players field. I want to know what are the conditions and requirements for this kind of scenario. What are the steps should I follow? For now, players are stored as we select them (so first selected goes first). I also want to save the order after drag and drop, any suggestions or question improvements will be a great support. Models.py class Group(TimeStampModel, PermissionsMixin): name = models.CharField(_("Group name"), blank=False, max_length=127, unique=False) phase = models.ForeignKey("Phase", related_name="groups", on_delete=models.CASCADE, blank=False, null=True) class Meta: ordering = ["name"] Forms.py: I'm using modelMultipleChoiceField for now. class GroupCreateForm(ModelForm): players = ModelMultipleChoiceField(queryset=None, help_text=_("Please hold down 'Control', to select more than one player")) def save(self, commit=True): group = super(GroupCreateForm, self).save(False) group.phase = self.instance.phase group.created_by = get_request().user if commit: group.save() if self.instance: for player_id in self.cleaned_data['players']: player = Player.objects.get(pk=player_id) ranking = GroupRanking(order=0, player=player, group=group) ranking.save() # Trigger a compute on saving group.phase.ruleset.computeScores() return group class Meta: model = Group fields = ("name",) views.py class GroupCreateView(AccessControlMixin, CreateView): model = Group form_class = GroupCreateForm template_name_suffix = '_create' def has_access(self, user): return self.can(" ", self.phase.tournament) def get_success_url(self): return "%s" % reverse("tournaments:detail", kwargs={"pk": self.kwargs['pk']}) def dispatch(self, request, *args, **kwargs): self.phase = get_object_or_404(Phase, pk=kwargs['rpk']) return super(GroupCreateView, … -
Pagination causes duplicate elements in Django
I've the following ListView: class SentencesListView(ListView): model = Sentence paginate_by = 10 def get_queryset(self): return Sentence.objects.all().order_by('-proficiency') When the user interacts with the webpage, proficiency of all Sentences on the displayed page increases. As a result, when get_queryset will be called again (when user visits the next page), he'll see the same sentences as he did on the previous page. How can I prevent this? I've tried the following which didn't work: class SentencesListView(ListView): model = Sentence paginate_by = 10 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cached_query_set = None def get_queryset(self): if not self.request.GET.get('page') or not self.cached_query_set: self.cached_query_set = Sentence.objects.all().order_by('-proficiency') return self.cached_query_set self.cached_query_set is never not None when the test is performed inside get_queryset. Hence, the query set is always computed anew when moving to the next page. Is there a way to prevent users from experiencing duplicates? Or, is there a way to prevent get_queryset from being called when moving to the next page? -
Django The QuerySet value for an exact lookup must be limited to one result using slicing Error
I have this problem when I want to show all of the post that related to category. I couldn't find the solution in other similar questions. Thank you. Error: The QuerySet value for an exact lookup must be limited to one result using slicing. Model: class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) def get_absolute_url(self): return reverse("post", kwargs={'slug': self.slug}) View : class PostListView(ListView): """ Return all of the posts """ model = Post ordering = '-created' context_object_name = 'posts' template_name ='blog/post_list.html' def get_queryset(self): qs = Post.objects.all() if self.kwargs.get('slug'): category_slug = self.kwargs.get('slug') qs = Post.objects.filter(category = Category.objects.filter(slug = category_slug)) return qs URL: path('', PostListView.as_view(), name='posts'), # all of the posts path('category/<slug:slug>/', PostListView.as_view(), name='categoryposts'), Template: <div class="row"> {% for post in posts %} <div class="col-md-4"> <div class="card" style="width: 25rem; height: 34rem;"> <a href="{% url 'post' post.slug %}"> <img class="post-thumbnail card-img-top" src="{{post.thumbnail.url}}" alt="{{post.title}}" style="width: 24.9rem; height: 18rem;"> </a> <div class="card-body"> <h5 class="card-title"><a href="{% url 'post' post.slug %}">{{post.title}}</a></h5> <p class="post-updated">Last update at {{post.updated|date:"Y/M/d"}}</p> <p>Post by <a href="">{{post.author}}</a></p> {% if post.description %} <p class="card-text">{{post.description|slice:"80"}}...</p> {% else %} <p class="card-text">{{post.body|slice:"80"}}...</p> {% endif %} <a href="{% url 'post' post.slug %}" … -
django: get() returned more than one Freelancers -- it returned 3
i am trying to assign a freelancer to a particular gig but it shows get() returned more than one Freelancers -- it returned 3!. I have tried getting the logged in freelancer to is trying to create the git like this freelancer = get_object_or_404(Freelancers, user=user) and before i save the form i assign the value like this new_form.creator = freelancer . views.py @login_required def create_gig(request): user = request.user freelancer = get_object_or_404(Freelancers, user=user) if request.method == "POST": form = CreateGig(request.POST, request.FILES) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user new_form.creator = freelancer new_form.slug = slugify(new_form.title) new_form.save() messages.success(request, f'Gig Created Successfully, Would be Live Soon') return redirect('freelance:listings') else: form = CreateGig() context = { 'form': form } return render(request, 'freelance/create.html', context) models.py class Gigs(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='gig_user') creator = models.ForeignKey(Freelancers, on_delete=models.CASCADE, related_name='gig_creator') title = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Enter what you will do", default=" I will ")