Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: unsupported operand type(s) for +: 'float' and 'list' how to solve it in django?
I have a question for you. I have the following class: class StatoPatrimoniale(models.Model): reference_date=models.DateField() income=models.DecimalField() debt=models.DecimalField() After that I have named a new variable last_account_year in th following manner: now=datetime.datetime.now() last_account_year=float(now.year)-1 After that I have created the following code: if StatoPatrimoniale.objects.filter(reference_date__year=last_account_year).count()>0: list_diff = float(StatoPatrimoniale.objects.filter(reference_date__year=last_account_year).values_list('crediti_commerciali')[0][0]) else: list_diff=[0]+list_diff crediti_commerciali = {} crediti_commerciali['Crediti Commerciali'] = list(accumulate(list_diff)) But give me the following error: unsupported operand type(s) for +: 'float' and 'list' How could I solve it? -
Google Maps with Django
i'm trying to link google maps with my location point field rather then leaflet, bacause google maps is having a better functionality at my area. am going to link that with my forms.py to make users be able to select their location and submit it on a model-form. any suggestions on how i could do that with Geo-django ? models.py from django.contrib.gis.db import models class ShippingAddress(models.Model): name = models.CharField(max_length=200, null=False) location = models.PointField() forms.py class AddAddress(forms.ModelForm): location= forms.PointField(label="", widget = ...) name = forms.CharField(label="") class Meta: model = ShippingAddress fields = ('location', 'name') -
Image uploading from Django-template to model is not working
I am trying to upload profile image of user from userprofile.html template but it is not uploading to that model on admin panel. I already configured the static and media settings correctly. #forms.py class ImageUploadForm(forms.ModelForm): class Meta: model = accountUser fields = ['profile_photo',] #views.py def upload_pic(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('success') else: form = ImageUploadForm() return HttpResponseForbidden('allowed only via POST') #user.html <form method = "post" enctype="multipart/form-data"> {% csrf_token %} <p> <input id="id_image" type="file" class="" name="image"> </p> <button type="submit">Choose Picture</button> </form> -
Cannot resolve keyword 'username' into field. Choices are: bio, blog, describtion, id, image, speciality, status, user, user_id
hey i want to create a profile page for my user,in which when people logging to the website they can view the profile of every user,i get the above error anytime i tried to log on to every profile of the user i get it, this is my code below views.py class DoctorDetailView(LoginRequiredMixin, DetailView): model = Doctor fields = ['user', 'email', 'image', 'speciality', 'bio'] template_name = 'pages/doctor_detail.html' def get_queryset(self): user = get_object_or_404(Doctor, username=self.kwargs.get('username')) return Doctor.objects.filter(doctor=user.doctor) urls.py path('doctor/', doctor, name='doctor'), path('doctor/info/<str:username>', user_views.DoctorDetailView.as_view(), name='doctor-detail'), doctor.html <a href="{% url 'doctor-detail' doc.user.username %}"><div class="img-wrap d-flex align-items-stretch"> <div class="img align-self-stretch" style="background-image: url({{ doc.user.doctor.image.url }}"></div> models.py class Doctor(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="doctor") image = models.ImageField(default='jazeera.jpg', upload_to='profile_pics') bio = models.TextField() speciality = models.CharField(max_length=300) describtion = models.CharField(max_length=100) status = models.ManyToManyField(Status) def __str__(self): return f'{self.user.username}' -
Django viewset error: 'QuerySet' object has no attribute 'title'
I'm trying to create a ViewSet for the Course model (to simply display all courses), but I'm getting the following error when trying to access it. I'm new to creating ViewSets and Django in general, what am I doing wrong? Error AttributeError: Got AttributeError when attempting to get a value for field `title` on serializer `CourseSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'title'. CourseViewSet class CourseViewSet(viewsets.ModelViewSet): def list(self, request): queryset = Course.objects.all() serializer = CourseSerializer(queryset) return Response(serializer.data) CourseSerializer class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ( 'id', 'title', 'description', 'active', 'individual_result', 'course_duration', 'video', 'manager_id' ) models/Course class Course(models.Model): title = models.CharField(max_length=255, blank=False, null=False) description = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) individual_result = models.BooleanField(default=False) course_duration = models.CharField(max_length=255, blank=True, null=True) video = models.CharField(max_length=255, blank=True, null=True) manager_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.title -
Django Rest Framework - Serialize intermediate model fields (to POST or GET)
I am trying to handle POST and GET requests of my SalesProject model, which has a M2M field to CustomerInformation model, with an intermediate model of ProjectCustomer. I am wondering if there are any ways for me to be able to create a new SalesProject instance, and add the relevant instances of CustomerInformation to that created SalesProject instance, just like how it would have been done before I switched it to an intermediate model. Basically, this is the data that I would want to pass in for the POST request {sales_project_name: "Test Project", customer_information: [1, 2]} where [1,2] is the id of the CustomerInformation instance that I want to link M2M to that particular SalesProject I am creating Here is my models.py class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) history = HistoricalRecords() class SalesProject(models.Model): sales_project_id = models.AutoField(primary_key=True) sales_project_name = models.CharField(max_length=100) customer_information = models.ManyToManyField('CustomerInformation', through='Project_Customer') history = HistoricalRecords() class Project_Customer(models.Model): project = models.ForeignKey('SalesProject', on_delete=models.SET_NULL, null=True) customer = models.ForeignKey('CustomerInformation', on_delete=models.SET_NULL, null=True) history = HistoricalRecords() I am new to using intermediate models, so do guide me along if I am mistakened about anything! From what I see, it seems like when I try to create a SalesProject using ModelViewsets, the customer_information field … -
AttributeError: function 'initGEOS_r' not found
Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\gis\admin\__init__.py", line 5, in <module> from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\gis\admin\options.py", line 2, in <module> from django.contrib.gis.admin.widgets import OpenLayersWidget File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\gis\admin\widgets.py", line 4, in <module> from django.contrib.gis.geos import GEOSException, GEOSGeometry File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\gis\geos\__init__.py", line 5, in <module> from .collections import … -
SQL - Django Movie Booking System
I am currently working on movie booking site that allows user to book movie tickets at different time and date. I have already created the model for theater, seats, movie, and for movie date availability. I am wondering if; for every different time in a day: Example: - 12:30 PM - 3:00 PM - 5:30 PM It means for every theater in that 'time' i will create new seats for booking, just to get track on what seats are still available? Imagine, a theater-1 with capacity of 100 seats, that means that on 12:30 PM, a hundred seats are created. And at 3:00 PM, a different sets of seats are also created. That means that i will have a total of 200 seats, or 200 seats object on my database. Also the same scenarios on different dates, and theater number. Is there any way to reduce the number of data? Or my analyzation is wrong? -
Django aggregate Avg vs for loop with prefetch_related()
I have a Review model that is in one to one relationship with Rating model. A user can give a rating according to six different criteria -- cleanliness, communication, check_in, accuracy, location, and value -- which are defined as fields in the Rating model. class Rating(models.Model): cleanliness = models.PositiveIntegerField() communication = models.PositiveIntegerField() check_in = models.PositiveIntegerField() accuracy = models.PositiveIntegerField() location = models.PositiveIntegerField() value = models.PositiveIntegerField() class Review(models.Model): room = models.ForeignKey('room.Room', on_delete=models.SET_NULL, null=True) host = models.ForeignKey('user.User', on_delete=models.CASCADE, related_name='host_reviews') guest = models.ForeignKey('user.User', on_delete=models.CASCADE, related_name='guest_reviews') rating = models.OneToOneField('Rating', on_delete=models.SET_NULL, null=True) content = models.CharField(max_length=2000) I am thinking of a way to calculate the overall rating, which would be the average of average of each column in the Rating model. One way could be using Django's aggregate() function, and another option could be prefetching all reviews and looping through each review to manually calculate the overall rating. For example, for room in Room.objects.all() ratings_dict = Review.objects.filter(room=room)\ .aggregate(*[Avg(field) for field in ['rating__cleanliness', 'rating__communication', \ 'rating__check_in', 'rating__accuracy', 'rating__location', 'rating__value']]) ratings_sum = 0 for key in ratings_dict.keys(): ratings_sum += ratings_dict[key] if ratings_dict[key] else 0 Or, simply looping through, rooms = Room.objects.prefetch_related('review_set') for room in rooms: reviews = room.review_set.all() ratings = 0 for review in reviews: ratings += (review.rating.cleanliness + … -
I want to filter my Disciplina datas by id but appear this error FieldError at /admin-note/4 Cannot resolve keyword 'id' into field
I know that i must make a foreign key but i dont know how, the student id works, but dont have in my disciplina model and i dont know how i can make a fk in the model and filter by this. ########## view of this route ######### login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_note(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) students=models.StudentExtra.objects.all().filter(id=pk) materias= models.Disciplina.objects.all().filter(id=pk) #i want to filter by id here return render(request,'school/admin_note.html', {'students': students, 'materias': materias, 'pk':pk}) ########## models ################# classes=[('maternalzinho','maternalzinho'),('maternal1','maternal1'),('maternal2','maternal2'), ('1periodo','1periodo'),('2periodo','2periodo'),('1ano','1ano'),('2ano','2ano'),('3ano','3ano'),('4ano','4ano'),('5ano','5ano')] class StudentExtra(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) roll = models.CharField(max_length=540) mobile = models.CharField(max_length=40,null=True) fee=models.PositiveIntegerField(null=True) cl= models.CharField(max_length=145,choices=classes,default='maternalzinho') status=models.BooleanField(default=False) respon= models.CharField(max_length=540, null=True) localnasc= models.CharField(max_length=540, null=True) estado = models.CharField(max_length=540, null=True) sexo= models.CharField(max_length=540, null=True) mae= models.CharField(max_length=540, null=True) emailrespon= models.CharField(max_length=200, null=True) cpfrespon= models.CharField(max_length=200, null=True) bairro= models.CharField(max_length=200, null=True) cidade= models.CharField(max_length=200, null=True) datenasc= models.CharField(max_length=540, null=True) @property def get_name(self): return self.user.first_name @property def get_id(self): return self.user.id def __str__(self): return self.user.first_name materia=[('lingua portuguesa','lingua portuguesa'), ('matematica', 'matematica'), ('ciencias', 'ciencias'), ('historia', 'historia'), ('geografia', 'geografia'), ('ingles', 'ingles'), ('artes', 'artes'), ('informatica', 'informatica'), ('recreacao', 'recreacao') ] class Disciplina(models.Model): codisc = models.AutoField(primary_key=True) nome_disc = models.CharField(max_length=540,choices=materia,default='lingua portuguesa') enter image description here -
Django: Reconstructing a form with ModelChoiceField from database
I have a Django form that contains several CharFields and ModelChoiceFields. Once the user has submitted the form, some calculations take place and the information is stored in the database. Since the form contains many fields, I would like to add the functionality that the user can reconstruct the form at a later point, change some settings and resubmit it. In my views.py, I check whether the form has been submitted before. If yes, I fill a dictionary with initial data from the database and then create an instance of the form. initialData = {} initialData['title'] = databaseObject.title ... ... form = myForm(initial = initialData) This works for the CharFields, but it does not work for the ModelChoiceFields. They are just empty. I cannot figure out how to put the queryset and the previously selected choice into the initialData dictionary so that the ModelChoiceFields are correctly populated and the correct choice is selected. -
Python, filter queryset and set equal to zero if empty
I'm using the following code to filter my queryset: liquidity[element][0] = float(StatoPatrimoniale.objects.filter(reference_date__year=last_account_year).values_list('cassa')[0][0]) But If the queryset does not exist, python give me error. So I want to add the best solution to set liquidity[element][0]equal to zero if the queryset is empty. What is it the best solution? -
Get FOREIGN KEY constraint failed when try to save, but same code works on shell
I'm getting this error FOREIGN KEY constraint failed when trying to save some records to database, but similar code works fine when manually run in the shell. My code below: Models.py from django.contrib.auth.models import User from sde.models import Invtypes from corp.models import EveCharacter class Cart(models.Model): client = models.ForeignKey(User,on_delete=models.CASCADE) item = models.ForeignKey(Invtypes,on_delete=models.CASCADE) quantity = models.IntegerField(default=1,blank=False,null=False) price = models.IntegerField(default=0,blank=True,null=True) checkout = models.BooleanField(default=False) createdate = models.DateTimeField(auto_now_add=True,blank=True) @property def get_total_price(self): return self.price * self.quantity def __str__(self): return '%s x %s' % (self.item,self.quantity) class Order(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4,help_text="UID") user = models.ForeignKey(User,on_delete=models.CASCADE) receiver = models.ForeignKey(EveCharacter,on_delete=models.CASCADE) totalprice = models.IntegerField(default=0,blank=False,null=False) ORDER_STATUS = ( ('o','on hold'), ('f','finished'), ('c','canceled'), ('e','exception'), ) status = models.CharField(max_length=1, choices=ORDER_STATUS, blank=True, default='o') createdate = models.DateTimeField(auto_now_add=True,blank=True) finishdate = models.DateTimeField(blank=True,null=True) class Meta: ordering = ["createdate"] def get_absolute_url(self): return reverse('order-detail', args=[str(self.uid)]) def __str__(self): return '%s (%s-%s)' % (self.receiver,self.status,self.uid) class OrderUnit(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) order = models.ForeignKey('Order',on_delete=models.CASCADE) item = models.ForeignKey(Invtypes,on_delete=models.CASCADE) quantity = models.IntegerField(default=0,blank=False,null=False,help_text="product amount") price = models.IntegerField(default=0,blank=False,null=False) ITEM_STATUS = ( ('w','Waiting for processing'), ('s','Sent'), ('p','Partially Sent'), ('e','Out of stock'), ) status = models.CharField(max_length=1, choices=ITEM_STATUS, blank=True, default='w') def __str__(self): return '%s x %s (%s-%s)' % (self.item,self.quantity,self.status,self.uid) Views.py @login_required def create_order(request): if request.method == 'POST': cartlist = request.POST.getlist('cart') #Get a list of submitted items character = EveCharacter.objects.get(name=request.POST.get('character')) #Get recipient … -
Django path when opening files
So I have this function which should return the pdf file the user has uploaded; def pdf(request, filepath): print('pdf view') print('---------', filepath) try: return FileResponse(open(filepath, 'rb'), content_type='application/pdf') except FileNotFoundError: raise Http404('not found') ### path in urls.py; path('pdf/<path:filepath>/', pdf, name='pdf') Output; pdf view --------- documents/1/CV_2020-01-30-101435_LTGzySn.pdf/' Not Found: /cv_upload/pdf/documents/1/CV_2020-01-30-101435_LTGzySn.pdf/'/ Expected Output: anything but the leading /cv_upload/pdf/. Why is the path suddenly changed to an arbitrary path with the function's name and how can I prevent this ? -
Python and django, how to extract data from the queryset
I have a question for you. I have the following class: class StatoPatrimoniale(models.Model): reference_date=models.DateField() income=models.DecimalField() debt=models.DecimalField() After that I have named a new variable last_account_year in th following manner: now=datetime.datetime.now() last_account_year=float(now.year)-1 Now I want to create a function that give me the possibility to extract the incomeand debt objects filtering them using the last_account_year and the year in the reference_date. How could I get this result? -
Are Django MySQL DB operations thread safe?
Background I am creating project where Django app must be integrated with some sort of IP cameras and other TCP/IP devices. (Either WEB api or low level Sock TCP/IP). There are some threads being run through WSGI or possibly being started with the user interaction. These threads collect data from given devices and then enqueue tasks to the Redis queue. In the queue data is being processed, there are some db requests made and model creation. I am using a MySQL database. I did not find any information here but possibly missed it. Problem Do I need to care about thread safety when I make requests to the DB ? (Basic model creation, Models filtering and searching), as they would access the same table and the same data? Right now all of the threads enqueue tasks to one queue. . I wanted to know if there will be problem when 2-6 threads are making requests or multiple queues instead of a one queue ? One queue in the beginning of the development process was fine but the task function starts to become unclear and hard to extend. I want to separate it thus separating one queue into multiple ones, and … -
'__proxy__' object has no attribute 'get'
Im getting this error when my SignUp View returns the reverse_lazy function: AttributeError at /signup/ '__proxy__' object has no attribute 'get' My view: class SignUpView(View): def get(self, request, *args, **kwargs): return render(request, 'accounts/signup.html', context = {'form':UserCreateForm}) def post(self, request, *args, **kwargs): print(f'request: {request.POST}') form = UserCreateForm(request.POST) if form.is_valid(): user = form.save(commit = False) user.username = request.POST.get('email') user.save() return reverse_lazy('homePage') The form: class UserCreateForm(UserCreationForm): class Meta(): fields = ('first_name', 'last_name', 'email', 'departments', 'password1', 'password2') model = get_user_model() User model: class User(AbstractUser): departments = models.ManyToManyField(Department) def __str__(self): return f'{self.first_name} {self.last_name}' What is causing the error? -
How can I use foreign keys attribute in same model
How can I use the vehicle's attributes in default ? class Orders(models.Model): vehicle = models.ForeignKey(Vehicles, on_delete= models.CASCADE) exit_km = models.IntegerField(default=vehicle.current_km) -
Django 3.0.3: NoReverseMatch at / : Reverse for 'post_new' with no arguments not found. 1 pattern(s) tried:
Need Help. I am not passing an argument while using href but still url pattern is looking for an argument. Master urls.py urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^$',include('portfolio.urls')), re_path(r'accounts/login/$',LoginView.as_view(),name='login'), re_path(r'accounts/logout/$',LogoutView,name='logout',kwargs={'next_page':'/'}) ] Portfolio.urls urlpatterns = [ re_path(r'^$',views.PostListView.as_view(),name='post_list'), re_path(r'^about/$', views.AboutView.as_view(),name='about'), path ('post/new/',views.CreatePostView.as_view(),name='post_new'), re_path (r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),] <nav class="navbar navbar-dark bg-dark"> <div class ="container"> <ul class= "navbar navbar-dark bg-dark"> <li><a class='navbar-brand' href="{% url 'post_list' %}"> My Blog </a> <li><a href="https://www.github.com/">Github</a></li> <li><a href="https://www.linkedin.com/">Linkedin</a></li> </ul> <ul class='nav nsvbsr-right'> {% if user.is_authenticated %} <li> <a href="{% url 'post_new' %}">New Post </a> <a href="{% url 'post_draft_list' %}">Draft </a> <a href="{% url 'logout' %}">Log Out</a> </li> <li> <a> Welcome : {{ user.username }} </a> </li> {% else %} <li> <a class='nav nsvbsr-right' href="{% url 'login' %}"> Login </a> </li> {% endif %} </ul> </div> </nav> I am getting the following error: In Short: Page throws the error after user logs in (i.e. is_authenticated is true). Models.py class CreatePostView(LoginRequiredMixin, CreateView): login_url="/login/" redirect_field_name="portfolio/post_detail.html" form_class = PostForm model = Post -
Identity Server functionality in Djnago
i am creating API for djnago project i at a time multiple users . one user is mobile and others are end users. i have no username and password for log in. i want to generate token using client_id and client_secret. like identity server in .net core. How can i implement this. i tried Django-oauth-toolkit . But i am not getting the detail working of this i created multiple client , with client_id and client_secret. after that i didn't understand the following then how can i create token using this ? which URL is used ? after token created,what is next ? how can i authorize the token ? which url is used? i am using postman or checking -
django-tables2: order_by custom column
I have a very similar question to here, but I was not able to solve it with it. I have a tables.py file looking like this: class CurrencyColumn(django_tables2.Column): def render(self, value): return "{:0.2f} €".format(value) class SetTable(django_tables2.Table): total_price = CurrencyColumn(accessor="total_price", verbose_name="total", attrs={"td": {"align": "right"}}) name = django_tables2.LinkColumn("set-detail", args=[django_tables2.A("pk")]) class Meta: model = Sett sequence = ("name", "total_price") exclude = ("id",) corresponding views.py looks like this: class SetListView(SingleTableView): model = Sett table_class = SetTable I cannot click on "total" to order the column, I know this is because it is shown using the "accessor". My question is, where and how to implement an order method so I can order ascending/descending total values? -
Foreign-key automatically fill in the form step by step
I have four models of the shop, customer, product, an order. I am showing the relation of models shop user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) customer user = models.OneToOneField(User, null=True, on_delete=models.CASCADE product shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) order shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) when customers login then the shop will print on the screen and a button on shop to show the products by the shop in the form card. On the product card, there is an order button that adds the product in order after submitting the selected product will print with the remaining filled of order that show in the image how I can create an order form so that the customer in order is the instance and the shop in order is that shop which is selected to show the products, and products which are selected for the order, please explain me step by step -
Compile Django program for Raspberry Pi using Pyinstaller
Has anyone achieved this on the RPi? I have tried this and the RPi returns me this error: Fatal error: PyInstaller does not include a pre-compiled bootloader for your platform. For more details and instructions how to build the bootloader see <https://pyinstaller.readthedocs.io/en/stable/bootloader-building.html> I have read the docs and I think I have correctly installed the bootloader, but the last time I ran it, it stucks on 299166 INFO: Building PKG (CArchive) PKG-00.pkg and it actually takes about two hours and still, and the file is about 10 GB, which is way longer than all the project, that is about 250MB... Any cue of what I should do? -
Djangop Heroku, when sending an e-mail, we get an error 500, how to fix?
When I sent letters from the local server, everything worked, uploading the project on heroku, when sending a letter to the mail we get this error Server Error (500) how to fix ?? form <form action="{% url 'app:get_ticket' session.id place.id price_total %}" method="get" > {% csrf_token %} <div class="input-group"> <input type="email" name="email_input" class= "input-email" id="formGroupExampleInput" placeholder="E-mail" required> <div class="input-group-append"> <button class="btn btn-success" type="submit">{% trans 'Забронювати' %}</button> </div> </div> </form> setings.py 2020-06-16T13:30:39.449419+00:00 app[web.1]: 10.8.240.17 - - [16/Jun/2020:16:30:39 +0300] "GET /en/get_ticket/46/16696/74/?csrfmiddlewaretoken=yxAUxEiQBsl5sQTUeNmrVXXhJWa0fd1iankeN38JrMk35kCb3iXMK1BEO9mAO1MH&email_input=reabko17%40gmail.com HTTP/1.1" 500 145 "https://cinemaxpro.herokuapp.com/en/reservation_ticket/3/46/1/16696/1" "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36" 2020-06-16T13:30:39.450237+00:00 heroku[router]: at=info method=GET path="/en/get_ticket/46/16696/74/?csrfmiddlewaretoken=yxAUxEiQBsl5sQTUeNmrVXXhJWa0fd1iankeN38JrMk35kCb3iXMK1BEO9mAO1MH&email_input=reabko17%40gmail.com" host=cinemaxpro.herokuapp.com request_id=700a9c23-2486-4ecf-b73b-ab79539f483c fwd="176.120.63.253" dyno=web.1 connect=0ms service=82ms status=500 bytes=402 protocol=https -
Django unit test with payload value (and parameter in url)
I got following endpoint. I pass a token in my request payload: As you can see there is a bug in the data and I want to test this with unit tests to find the bug. My test: def test_create_firebase_token(self, fcm_mock): c = Client() token = "dummytoken" python_dict = {"1": {"user_pk": self.author.pk, "token": token}} c.post("/firebase", json.dumps(python_dict), content_type="application/json") as you can see the original url is "users/{user_id}/firebase" How can I test this endpoint correctly? Because the parameter in the url I'm confused.