Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get sql query value in Django
how can I get only the value of the following query. I just want to get the value of name, and not a dict, since in laravel you can use the -> get () in django that I can use. with connection.cursor() as cursor: cursor.execute("SELECT name FROM person WHERE id=2") fila=cursor.fetchall() Thanks. -
Data migrations for OneToOneField in django with data in tables already
I have a case model that I added a OntToOneField to Example: zoho_api = models.OneToOneField( ZohoAPIState, default=create_new_zoho_api_state, related_name='referral_profile', on_delete=models.CASCADE ) During development there was no data in the tables and the migration worked fine. But trying to migrate with data in the tables gives me the following errors: Errors Says DETAIL: Key(zoho_api_id)=(some guid) is duplicated. How do I get around this issue? -
Items remain in the lists even after using del statement
I'm building an app using Python and Django and I'm facing a problem with some variables. Below are simpldified portions from my code to explain the problem (you can access the complete code in the repo): # resources.py class HREmployeeResource(ModelResource): def after_import_row(self, row, row_result, row_number=None, **kwargs): row_result.employee_code = row.get('Employee Code') if not kwargs.get('dry_run'): import_type = row_result.import_type employee_code = row_result.employee_code instance = kwargs.get('instance') # we need the ones belong to these 2 companies in the report if instance.company in ['Company 1', 'Company 2']: self.report.setdefault(import_type, []).append(employee_code) # views.py import gc from resources import HREmployeeResource def import_hr_file(request): if request.method == 'POST': hr_file = request.FILES['hr-file'] data = get_import_data(hr_file) hr_resource = HREmployeeResource() result = hr_resource.import_data(data, dry_run=True) if not result.has_errors(): result = hr_resource.import_data(data, dry_run=False) ImportStatus.objects.create( date=timezone.now(), status='S1', data=hr_resource.report ) del result, hr_resource, data gc.collect() return redirect('core:import-report') return render(request, 'core/upload-hr-file.html', {}) The ModelResource class is from a third-party library called django-import-export and the import_data method belongs to this class, you could find the code of the method here. When I run the view import_hr_file for the first time everything is working fine, but when I execute it the second time I find that the old items still exist in the lists of the report dict of the … -
how to request session value in template django
i want to fetch a session value directly in myy template i have fom by which i request session and after that i am viewing that session in another html my views.py where session got created class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.order_by('-update_at') return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('Size') cart = request.session.get('cart') if cart: cart[item] = size else: cart = {} cart[item] = size request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my views.py in which i want ot render session class Cart(View): def get (self, request): cart = request.session.get('cart', None) if not cart: cart = {} # or however you define your empty cart request.session['cart'] = cart ids = (list(cart.keys())) ids = (list(request.session.get('cart').keys())) item = Item.get_items_by_id(ids) print(item) return render(request, 'cart.html', {'items': item }) my html code {% for item in items %} <tbody style="margin-bottom: 20px;"> <tr> <th scope="row">{{forloop.counter}}</th> <td> <img src="{{item.first.url}}" alt="" height="100px"></td> <td>{{item.name}}</td> **<td>{{request.session.cart}}</td>** <td>{{item.price|currency}}</td> <td> <a href="#">Remove</a> </td> </tr> </tbody> {% endfor %} </table> </div> </div> so my session list has two values in it one is id and other is its size so want … -
Django FileField does not save unless in debug mode
I'm trying to upload files in Django 3.2 and am having a weird problem where the files save to the MEDIA_ROOT folder when I have the debugger on and set a breakpoint. But if I just run the project, then the files don't save. I cannot workout what is going on, but I would guess some sort of timing/threading issue? Any help appreciated. I have put my code below. I'm using FormModels to generate the forms and a Formset to allow multiple images to be uploaded. Models class TimestampedModel(d_models.Model): created_date = d_models.DateTimeField(auto_now_add=True) updated_date = d_models.DateTimeField(auto_now=True) class Meta: abstract = True class Case(TimestampedModel): class CaseType(d_models.IntegerChoices): One = 0, d_translation.gettext_lazy('One') Two = 1, d_translation.gettext_lazy('Two') # __empty__ = d_translation.gettext_lazy('Other') reference = d_models.CharField(max_length=32, editable=False) case_type = d_models.IntegerField(choices=CaseType.choices) def get_file_path(instance, file): return '{0}/{1}_{2}'.format(datetime.datetime.today().strftime('%Y-%m-%d'), uuid.uuid4().hex, file) class SourceMedia(TimestampedModel): class SourceMediaType(d_models.IntegerChoices): Image = 0, d_translation.gettext_lazy('Image') Video = 1, d_translation.gettext_lazy('Video') case = d_models.ForeignKey(Case, on_delete=d_models.CASCADE) mime_type = d_models.CharField(max_length=50, null=True) media_file = d_models.FileField(upload_to=get_file_path) Forms: class CaseForm(d_forms.ModelForm): def __init__(self, *args, **kwargs): super(CaseForm, self).__init__(*args, **kwargs) class Meta: model = models.Case fields = ['case_type'] class SourceImageForm(d_forms.ModelForm): @classmethod def create_formset(cls, extra, max_num): formset = d_forms.modelformset_factory(models.SourceMedia, form=SourceImageForm, extra=extra, max_num=max_num) return formset class Meta: model = models.SourceMedia fields = ['media_file'] View def case_create(request): source_media_formset = forms.SourceImageForm.create_formset(extra=5, … -
Dependent Chained Dropdown Select List with Django - Not working
I am trying to build a dependant dropdown in a django form, but it is not working. I have followed videos and tutorials, but got no luck. I would like to select a brand of a car (make) and then a model of a car. The model depends on the car's brand, of course. I have followed this tutorial https://python.plainenglish.io/python-and-django-create-a-dependent-chained-dropdown-select-list-b2c796f5a11 Status: The "Make" dropdown works fine. The "Model" dropdown is never showing anything. It just does not work, but no error is shown... :S models.py from django.db import models from django import forms class Vehicle(models.Model): make = forms.CharField(max_length=30) model = forms.CharField(max_length=30) ...omitted forms.py from django import forms from .models import Vehicle import json def readJson(filename): with open(filename, 'r') as fp: return json.load(fp) def get_make(): """ GET MAKE SELECTION """ filepath = '/Users/alvarolozanoalonso/desktop/project_tfm/tfm/JSON/make_model_A.json' all_data = readJson(filepath) all_makes = [('-----', '---Select a Make---')] for x in all_data: if (x['make_name'], x['make_name']) in all_makes: continue else: y = (x['make_name'], x['make_name']) all_makes.append(y) # here I have also tried "all_makes.append(x['make_name']) return all_makes class VehicleForm(forms.ModelForm): make = forms.ChoiceField( choices = get_make(), required = False, label='Make:', widget=forms.Select(attrs={'class': 'form-control', 'id': 'id_make'}), ) ...omitted class Meta: model = Vehicle fields = ['make', 'is_new', 'body_type', 'fuel_type', 'exterior_color', 'transmission', 'wheel_system', 'engine_type', 'horsepower', … -
How do I allow partial updates via POST request in Django?
Working on a small Django app and I've been asked to set up partial updates via POST request. I'm aware that PATCH works for partial updates out of the box but I don't have access to the front end and that's not what I've been asked to do. I was told it's a quick one line change, so I'm assuming I have to update the serializer as explained in the DRF docs (https://www.django-rest-framework.org/api-guide/serializers/#partial-updates) but I'm not sure where to do that exactly. Serializers: from rest_framework import serializers from cat.models import Cat class CatSerializer(serializers.ModelSerializer): class Meta: model = Cat fields = ( 'id', 'name', 'breed', 'birth_date', 'added_at', 'description') Viewset: from rest_framework import viewsets from cat.serializers import CatSerializer from cat.models import Cat class CatViewSet(viewsets.ModelViewSet): queryset = Cat.objects.all().order_by('-birth_date') serializer_class = CatSerializer -
How to pass date string to datetime field in django?
I need the number (as integer) of users that signed up (User.date_joined) between '2016-01-01'(string) and '2016-04-01' (string) (both dates fully included) The below queries didn't give me accurate results, since the date_joined is datetime field User.objects.filter(date_joined__gte='2016-01-01',date_joined_lte='2016-04-01').count() User.objects.filter(date_joined__range('2016-01-01 00:00:00','2016-04-01 12:59:59')).count() I am new to django and python , want to know how to pass the string date values to datetime field and use of range function -
Django Database queries to 'default' are not allowed in SimpleTestCase
I tried running the following tests and they both fail. I don't understand the error because my view does not have a model included. view class ClassroomGradebookView(TemplateView): """for choosing first gradebook""" template_name = "gradebook/gradebookstart.html" urls urlpatterns = [ path('', views.index, name='index'), .... path('gradebookstart/', views.ClassroomGradebookView.as_view(), name='gradebookstart'), ] test class ClassroomGradebookTests(SimpleTestCase): def test_classroomgradebook_url_name(self): response = self.client.get(reverse('gradebook:gradebookstart')) self.assertEqual(response.status_code, 200) def test_classroomgradebook_status_code(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) error AssertionError: Database queries to 'default' are not allowed in SimpleTestCase subclasses. Either subclass TestCase or TransactionTestCase to ensure proper test isolation or add 'default' to gradebook.tests.ClassroomGradebookTests.databases to silence this failure. -
How to fix systemctl status error gunicorn when deploying the digital ocean
I'm deploying a django project on digital ocean. My project has the following structure: $/ flo-log/ logistics/ settings.py wsgi.py ... manage.py ... I created a user with sudo privilege.I encountered the error found an the attached file: enter image description here The error stated that there's no module called logistics however,I have a directory called logistics which contains the wsgi file. Please how do I fix this error? -
Django permission for member only
I use the default role access control from Django with decorator as : @is_allowed(accounts_allowed=AccountType.MYACCOUNT) It works well but there is a case where I have to add some restriction to let only project members acces my view. Here is how I've done : def isProjectMember(project, request): membersProjectsId = [project.member.id, project.member2.id, project.member3.id] if request.user.id in membersProjectsId: return False and in my view: if not isProjectMember(project, request): return HttpResponseForbidden() It woks fine but I would have liked to know if there would not be a more optimal way of proceeding? Thank you. -
Failure to send form information to Function in Django
please look at my codes I created a class to create comments, I also wrote Vivo and HTML codes, but whatever I do, the information is not registered. Does anyone know the reason ?? view funtion register comment in model admin def comment_view(request): comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): title_comment = comment_form.cleaned_data.get('title_comment') full_name = comment_form.cleaned_data.get('full_name') comment_text = comment_form.cleaned_data.get('comment_text') strengths = comment_form.cleaned_data.get('strengths') weak_points = comment_form.cleaned_data.get('weak_points') product_id = comment_form.cleaned_data.get('product_id') product: Product = Product.objects.get_by_id(product_id) CommentModel.objects.create(owner_id=request.user.id, product_id=product.id, title_comment=title_comment, full_name=full_name, comment_text=comment_text, strengths=strengths,weak_points=weak_points ) messages.success(request,'نظر شما با موفقیت ثبت شد') return redirect('/') context = {'comment_form': comment_form, 'title': 'ایجاد نظر جدید'} return render(request, 'comment.html', context) model comment class CommentForm(forms.Form): full_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'نام و نام خانوادگی خود را وارد کنید'})) title_comment = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'عنوان نظر خود را وارد کنید'})) comment_text = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'متن نظر خود را وارد کنید'})) strengths = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'نقاط قوت محصول را وارد کنید'})) weak_points = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'نقاط ضعف محصول را وارد کنید'})) product_id = forms.IntegerField(widget=forms.HiddenInput()) url comment path('new-comment', comment_view, name='new-comment'), forms comment class CommentForm(forms.Form): full_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'نام و نام خانوادگی خود را وارد کنید'})) title_comment = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'عنوان نظر خود … -
Django - How do I display data from a dictionary in views.py
I have a dictionary in my views.py that set up like this: def dctFormat(request): dct = {} dct1 = {} for data in MapData.objects.all().iterator(): dct[data.User_Number] = dct1 dct1["First_Name"] = data.First_Name dct1["Account_or_Gift"] = data.Account_or_Gift dct1["Child_Name"] = data.Child_Name return render(request, 'datamap.html', context=dct) In the model.py, the MapData model looks like this: class MapData(models.Model): # name of the table AccountType = models.TextChoices('AccountType', 'Account Gift') UserType = models.TextChoices('UserType', 'User Customer') User_Number = models.IntegerField() User_or_Customer = models.CharField(max_length=8, choices=UserType.choices) First_Name = models.CharField(max_length=30); Child_Relationship_With_Gift = models.CharField(max_length=20) Child_Name = models.CharField(max_length=20) Account_or_Gift = models.CharField(max_length=10, choices=AccountType.choices) Occasion_or_Purpose = models.TextField() City_State = models.CharField(max_length=30) How do I go about displaying the dictionary in my views.py on the front end in my HTML file? I've seen a few forums but none of them really helped. Essentially the dictionary should look like this: {'1': {'First_Name': 'Paula', 'Child_Name': 'Ari', 'Account_or_Gift': 'Gift'}, '2': {'First_Name': 'Jake', 'Child_Name': 'Luke', 'Account_or_Gift': 'Account'}...} So when I call on the dictionary, it'll display the data based on the corresponding number. -
how to create a comment system using drf
halo i'm working on a project that requires user to give a feedback whenever possible using django rest_framework but im getting an some difficulties doing that below is my code snippet & err msg ##mode file class Review(models.Model): school = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='review') name = models.CharField(max_length=250, blank=True, null=True) reviewer_email = models.EmailField() rating = models.CharField( max_length=250, blank=True, null=True) review = models.TextField() ##serializer file class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = ('name', 'review', 'id', 'reviewer_email', 'rating') ##apiView class ReviewAPIView(generics.CreateAPIView): serializer_class = ReviewSerializer permissions = [permissions.AllowAny] queryset = Review.objects.all() err msg return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: schoolDetail_review.school_id [04/Aug/2021 15:37:12] "POST /school-detail/add-review HTTP/1.1" 500 208720 can anyone help pls -
Appointment slots with a few object created
I want to build an app that make easier Teacher and Student to have an appointment. Teacher have to submit their availabilities. For example, make them allow to tell student I'm available for appointment such date at such hour. Student can see all their availabilities and then can choice the appointment. Here is my models.py : class Appointment(models.Model): class Meta: unique_together = ('teacher', 'date', 'timeslot') TIMESLOT_LIST = ( (0, '09:00 – 10:00'), (1, '10:00 – 11:00'), (2, '11:00 – 12:00'), (3, '12:00 – 13:00'), (4, '13:00 – 14:00'), (5, '14:00 – 15:00'), (6, '15:00 – 16:00'), (7, '16:00 – 17:00'), (8, '17:00 – 18:00'), (9, '18:00 – 19:00'), (10, '19:00 – 20:00'), ) student = models.OneToOneField('Student', null=True, on_delete=models.CASCADE) teacher = models.OneToOneField('Staff', null=True, on_delete=models.CASCADE) date = models.DateField() timeslot = models.IntegerField(choices=TIMESLOT_LIST) def __str__(self): return '{} {} {}. Etudiant : {}'.format(self.date, self.time, self.doctor, self.patient_name) @property def time(self): return self.TIMESLOT_LIST[self.timeslot][1] is_completed = models.BooleanField(default=False) is_confirmed = models.BooleanField(default=False) So when the teacher will fill their availabilities, this will create many appointment objects and student have to choice one of them. I was asking myself there is an other possibility to not create as much appointment objects ? -
How to fix a Django view that is not returning an HttpResponse Object? (CS50 Project 1)
I am receiving the following error when submitting a form. ValueError at /edit_entry/hi/ The view encyclopedia.views.edit_entry didn't return an HttpResponse object. It returned None instead. Here is the views.py that is triggering the error. def edit_entry(request, title): if request.method == "POST": form = NewEditEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title, content) return HttpResponseRedirect("/wiki/" + title) else: form = NewEditEntryForm() return render(request, "encyclopedia/edit_entry.html",{ "form": NewEditEntryForm(), "title": title, "content": util.get_entry(title) }) What is the issue and how can I fix it? (I also need help prepopulating the form with already existing data. I have tried using initial, but that has not worked. What is the best way to prepopulate the form with existing data?) -
Django serializer update method key error in validated_data
I m using django rest framework to provide api to multiple application. single models being shared with these applications. And every applications are using some fields that no other apps are using. I have to write update method on serializer and take action as per the fields value received from these apps. when i write the update method and in case django doesn't finds any key it throws error. let see the code: Model: class TaskChecker(models.Model): taskName=models.CharField(max_length=50) notified = models.BooleanField (default=False) isDeleteRequest = models.BooleanField (default=False) isDeactivateMe = models.BooleanField (default=False) isActive = models.BooleanField (default=False) class TaskSerializer(serializers.ModelSerializer): class Meta: model=TaskChecker fields='__all__' def update(self, instance, validated_data): isDeleteRequest = validated_data['isDeleteRequest'] do some task isActive= validated_data['isActive'] do some task now the scenario is at a time either i will get validated_data['isDeleteRequest'] or validated_data['isActive']. in that case i get key error. how to resolve the issue? if i dont get the key at that time i should not get error. please help. thank you so much.... -
How to create element in another model with django
I have a small question. That is actually making me scratch my head. So in my Database, I have the following models: Activity Bill Clients I think you are all seeing the relationship I am trying to create : A Bill has one client and one or more activities. Here is the trick to make this whole thing user-friendly I am trying to create Bills (with the url: Bill/new) that can be edited manually. So the user is sent to an HTML page with the basic Bill template and he has a table that can add some rows with the activity the time spent and its cost. There are three things I am trying to achieve. Generate automatically the ID of the Bill (it should be pk of Bill) but it seems it's not generated until I have pressed on save. When I save a Bill I want to save also the activities I have entered manually. When I save the Bill I would like to save it as a Word or PDF document in the database. Are these possible? Thanks all for reading and helping I am banging my head to figure out how to do all of this … -
ResolutionFailure error while installing Twilio again with other dependencies in django
I need to install twilio in my django-project. The project already has a Pipfile and pipfile.lock containing the other dependencies needed. When I try to install twilio using the command "pipenv install twilio" its gives a resolutionfailure error. The issue is that twilio requires the PyJWT version to be 1.7.1 but other dependencies require the version of PyJWT to be greater than 2 and less than 3. How do I manage to maintain different versions of the PyJWT version and How do I install twilio with the same? -
how to show one text 3 times or more with httprespons in django
How can I return something or text 2 or more times ? In this case, i have one text should be printed . I want to keep the return because i need to execute a function that returns either None or an Httpresponse in urls we have : path('happy/<str:name>/<int:times>', happy), in views we have : def happy(request , name ,times): response = f"you are great , {name}:)\n " return HttpResponse(response , content_type='text/plain') i need show text in the amount of times how do this? -
django-allauth signup error: filename must be a str or bytes object, or a file
I am using django-allauth for user login/signup. I didn't modify any .py files or template files in django-allauth. But when I tried to create a new user, the system throw out an error: Django Version: 3.0.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'MyBlog', 'allauth', 'allauth.socialaccount', 'allauth.account', 'widget_tweaks', 'imagekit', 'ckeditor', 'ckeditor_uploader', 'comment', 'channels', 'webssh'] 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'] Template error: In template /usr/local/lib/python3.8/dist-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 7 filename must be a str or bytes object, or a file 1 : <fieldset class="module aligned {{ fieldset.classes }}"> 2 : {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %} 3 : {% if fieldset.description %} 4 : <div class="description">{{ fieldset.description|safe }}</div> 5 : {% endif %} 6 : {% for line in fieldset %} 7 : <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %} {% for field in line %} {% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> 8 : {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif … -
How do you use a Custom Model Manager method for a related Many-to-Many model field?
I am working on a small project, mostly for learning, and I am running into an issue with accessing expected custom model manager methods on some related M2M type models. The application I am trying to implement is a travel calculator, that can determine total fuel requirements and weights for all vehicles in a particular trip. models.py ... from django.db import models from django.db.models import Sum # Create your models here. class TripManager(models.Manager): def get_vehicle_weight(self): return self.get_queryset().all().aggregate(total_weight=Sum('vehicle__weight')) def get_vehicle_fuel(self): return self.get_queryset().all().aggregate(total_fuel=Sum('vehicle__fuel')) class Vehicle(models.Model): """A vehicle may belong to multiple businesses and multiple trips at once.""" name = models.CharField(max_length=50, help_text="The common name of the vehicle.") fuel_capacity = models.IntegerField(default=0, help_text="The total fuel capacity in gallons.") burn_rate = models.FloatField(default=0, help_text="The burn rate of fuel in gal/h.") weight = models.FloatField(default=0, help_text="The weight of the vehicle in pounds.") def __str__(self): return self.name class Business(models.Model): """""" name = models.CharField(max_length=50, help_text="The name of the business.") def __str__(self): return self.name class EmployeeType(models.Model): """Employee types can belong to many businesses.""" name = models.CharField(max_length=50, help_text="The title/role of a type of employee.") def __str__(self): return self.name class Trip(models.Model): """A trip will be the primary object, composed of other objects that are associated with the trip.""" name = models.CharField(max_length=128) vehicles = models.ManyToManyField(Vehicle, … -
Please see if it is possible to print various options (no code) during the implementation of the Django shopping mall
I am a student who is learning Janggo. I'm asking you a question because I have a question while processing shopping mall options. The data for the ongoing project are as follows. Cardigan has two options, Size and Color, and I want to use Select in the template to import the Value of Size and Value of Color separately. I want to know if this is possible. For example, I would like to write: I wonder if it's possible, and if possible, I'd appreciate it if you could let me know how it can be implemented. -
<QuerySet [<Address: Shreyash>, <Address: Shreyash>]>": "Order.address" must be a "Address" instance
I have model related to that form what I want is to when user click on submit button from go submit and save in database but here I got error so what to achieve is a single address got submit in that instead of all the address which is linked with whit model choice field so any idea how i can achieve that here is my models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) item = models.ForeignKey(Item, on_delete=models.CASCADE ) address = models.ForeignKey(Address, on_delete=models.CASCADE) price = models.FloatField(blank=False) update_at = models.DateTimeField(auto_now=True, editable=False) def placeorder(self): self.save() def __str__(self): return self.user.username class Address(models.Model): eighteen_choice = { ('Yes','Yes'), ('No','No') } phoneNumberRegex = RegexValidator(regex = r"^\d{10,10}$") pincodeRegex = RegexValidator(regex = r"^\d{6,6}$") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='address') reciever_name = models.CharField(max_length=200, blank=False) phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=False) alt_phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=True) state = models.CharField(max_length=50, choices=state_choice, blank=False) pincode = models.CharField(validators = [pincodeRegex], max_length = 6, blank=False) eighteen = models.CharField(blank=False, choices=eighteen_choice, default='Yes', max_length=4 ) city = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=500, blank=False) locality = models.CharField(max_length=300, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username my views.py class Checkout(View): def post (self, request,): user = request.user address = Address.objects.filter(user=request.user) ids = … -
Reverse for 'app_list' not found. 'app_list' is not a valid view function or pattern name [duplicate]
How can I fix this error? NoReverseMatch at /tr/super/user/ Reverse for 'app_list' not found. 'app_list' is not a valid view function or pattern name.