Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to develop my simple booking system in django right
I really need help, can someone please guide me on how to develop a really really simple booking system in django? models.py class Listing(models.Model): title = models.CharField(max_length=50) content = models.TextField(max_length=755) price = MoneyField(max_digits=5, decimal_places=3) # avail_days = models.ForeignKey(Days, on_delete=models.CASCADE) def __str__(self): return self.title class Booking(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) listing = models.OneToOneField(Listing, on_delete=models.CASCADE) # day = models.OneToOneField(Days, on_delete=models.CASCADE) date_booked = models.DateField(auto_now_add=True) def __str__(self): return self.user.username please can someone help me develop the views.py? how would this go? thanks, I'd appreciate it. -
Mailchimp bulk mail to audience from Django
I have a Mailchimp account with some audiences on it, my question is how can I send mail to all subscribers of a given audience using API from Django? I'm using mailchipm3 library to add subscribers to the audience and it works, I can even log into Mailchimp, create a campaign and send it to the audience, but I cannot find how to send a pre-elaborated mail to that audience via API Any help will be appreciated, thanks in advance! -
Django Chroniker disconnects with Database after continuous operation
Please checkout the stack trace below. This is a very weird problem. Chroniker is running as a command under 'supervisor script'. It needs a process restart after every 2-3 days to keep working else it freezes and starts throwing the below error. The database was completely operational at the time and used by other processes in the normal fashion. ` [2020-06-03 01:57:16] Running due jobs... Exception in thread Thread-5007: Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/newrelic/hooks/database_dbapi2.py", line 101, in call *args, **kwargs), self._nr_dbapi2_module, (args, kwargs)) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/psycopg2/init.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "xxxxxxxxx.rds.amazonaws.com" to address: System error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/chroniker/management/commands/cronserver.py", line 19, in run call_command('cron') File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/core/management/init.py", line 148, in call_command return command.execute(*args, **defaults) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/newrelic/packages/wrapt/wrappers.py", line 508, in call args, kwargs) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/newrelic/api/function_trace.py", line 104, in literal_wrapper return wrapped(*args, **kwargs) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/chroniker/management/commands/cron.py", … -
Django webp converter tag static_webp not working
I installed the webp_converter package at documented Here {% load webp_converter %} This is not working which I want to add static_webp <img src="{% static_webp 'modelImage.url' %}"> This is working fine <img src="{{ modelImage.url }}"> From Official Doc says <img src="{% static_webp 'img/hello.jpg' %}"> -
Django REST framework - "Method \"GET\" not allowed." -
In creating Django REST framework, i'll get all the data using this code views.py @api_view(['GET', ]) def api_detail_educationlevel(request): if request.method == 'GET': educationlevel = EducationLevel.objects.all() serializer = EducationLevelSerializer(educationlevel, many=True) return Response(serializer.data) urls.py path('api/', views.api_detail_educationlevel), but when i add in my views.py like this @api_view(['PUT', ]) def api_update_educationlevel(request, pk): try: educationlevel = EducationLevel.objects.get(pk=pk) except EducationLevel.DoesNotExist: return HttpResponse(status=404) if request.method == 'PUT': serializer = EducationLevelSerializer(educationlevel, data=request.data) data = {} if serializer.is_valid(): serializer.save() data["success"] = "update successfull" return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['DELETE', ]) def api_delete_educationlevel(request, pk): try: educationlevel = EducationLevel.objects.get(pk=pk) except EducationLevel.DoesNotExist: return HttpResponse(status=404) if request.method == 'DELETE': operation = educationlevel.delete() data ={} if operation: data["success"] = "delete successfull" else: data["failure"] = "delete failed" return Response(data=data) @api_view(['POST', ]) def api_create_blog_view(request): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content) and in my urls.py urlpatterns = [ path('api/', views.api_detail_educationlevel), path('api/update/', views.api_update_educationlevel), path('api/delete/', views.api_delete_educationlevel), path('api/create/', views.api_create_blog_view), ] urlpatterns = format_suffix_patterns(urlpatterns) I dont know why i am getting this message, in my path('api/update/', views.api_update_educationlevel), in my path('api/delete/', views.api_delete_educationlevel), in my path('api/create/', views.api_create_blog_view), any idea why i am getting this message? i just want functional rest framework that can … -
how to substract two dates in django?
i am trying to subtracts 'end time' of a ride from its 'start time'. starttime is fetched directly from database(models.py) and line 'start = n[0].driverStarttime' indicates that. Now i use current datetime as 'endtime' of a ride. Variable 'diff' is used to subtract end and start time. but it gives 'TypeError at /driver_panel/endtrip can't subtract offset-naive and offset-aware datetimes' error. here driver_panel is my application in project. Driverbooking table is used to fetch start time. DateTimeField is used for store start and endtime. here is the code... def endtrip(request): if request.method == 'GET': dbid = request.GET.get('driverBookID') if dbid: n = Driverbooking.objects.all().filter(driverBookID=dbid) name = n[0].customerID start = n[0].driverStartTime end = datetime.datetime.now() diff = end - start total = diff * 10 a = Driverbooking.objects.get(driverBookID=dbid) a.driverStatus = "end" a.driverEndTime = end a.driverAmount = total a.save() did = request.session['uid'] x = Driverside.objects.all().filter(driverID=did) rate = x[0].driverFPH d = Driverside.objects.get(driverID=did) d.driverIsAvailable = "yes" d.save() context = {"name":name,"start":start,"end":end,"rate":rate,"t":total} return render(request, "driverbill.html", context) return redirect('driverhome') -
Making django web application accessible from other machines without deploying to a cloud
I have a django web application and normally, it works on AWS but one of our customers wants to use this web application on localhost because of the security. Also he wants to use this application with more than one computer on the same host. How to make a roadmap for that without sharing source code? -
What is the right way to link up an app in Django?
I'm somewhat a beginner with Django and I'm wondering why ppl link up apps in settings.py in INSTALLED_APPS in 2 different ways. One is just the name of the application and the other one 'appname.apps.AppnameConfig'. What is the difference between the two? -
Django - Serializing a M2M intermediate model (for POST, PUT and GET requests)
I am trying to include the data from the intermediate model of my M2M field inside my api calls, such that I would get the data from the M2M field in my GET request, and also be able to POST and PUT for that intermediate model when I am doing a POST and PUT request for my base model. 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 using model viewsets and model serializers for my SalesProject, shown below class SalesProjectViewSet(viewsets.ModelViewSet): serializer_class = SalesProjectSerializer queryset = SalesProject.objects.all() class SalesProjectSerializer(serializers.ModelSerializer): class Meta: model = SalesProject fields = '__all__' How would I be able to get the details of the CustomerInformation tied to the SalesProject instance through the M2M field? When I use this to get data, the SalesProject data only shows the other fields, while missing out the customer field. Also, when I POST data, how can I send both the SalesProject data and the customer instances that I want to link M2M … -
Could Djando admin site build a scheduling system?
Good day! I am a student and I approached a project wrong. I was aiming for a pyhon django scheduling system but what i actually did was a website for only notifyiing a fiven email address for a request about an appointment. I dont have any clue how to integrate what i did to run a scheduling system. I searched any google but i really cannot find any solution. maybe I am asking the wrong question? Could anyone please help me try and resolve my problem? could i still salvage what i worked on? -
How to create a magnifying glass beside a form field in admin change form to run a script
I'd like to put a search icon (like magnifiying glass) beside a field in the admin change form to let the users to trigger a script to fill other fields on demand only. I have to avoid triggering any field event (blur, click, change etc) on this field because it has to be triggered under user request, according to what he/she need. Django has its own magnifying glass icon/link for raw_field foreign key selection popup. Is it possibble to do something similar, where I would trigger the script upon the magnifying glass click. It will be just a JQuery to call a webservice and return values to be filled up on some other fields. I found one working solution by putting a custom button as a field, but it is placed far from the field because its label (what I seems weird for my purpose). Let me know if this description is enough or additional information is needed. example here Tks.