Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saleor Stripe integration shows only one payment method (card) while in test mode
I enabled the Stripe implementation for Saleor. I added the correct api-keys. The connection is working. But Saleor only shows 1 of multiple payment methods provided by Stripe. I am working in testmode so I expect all payment methods to be shown. Stripe marks them also with 'testmode' in their own environment. Someone had this problem before? Can't find any documentation about this problem. -
why does my app doesn't render my Tabs in Django?
I am trying to delevop a website containing few tabs in it. I am not getting how to render it in django. Tabs doesn't changes instead it jst reload. I have tried with various ideas i could get but its not leading me anywhere. html code: <ul class="nav nav-tabs text-center" role="tablist"> <li role="presentation" class="active"><a href="#tab01" aria-controls="tab01" role="tab" data-toggle="tab">Overview</a></li> <li role="presentation"><a href="#tab02" aria-controls="tab02" role="tab" data-toggle="tab">Itinerary</a></li> <li role="presentation"><a href="#tab03" aria-controls="tab03" role="tab" data-toggle="tab">Lodging</a></li> <li role="presentation"><a href="#tab04" aria-controls="tab04" role="tab" data-toggle="tab">Faq &amp; Review</a></li> <li role="presentation"><a href="#tab05" aria-controls="tab05" role="tab" data-toggle="tab">Gallery</a></li> <li role="presentation"><a href="#tab06" aria-controls="tab06" role="tab" data-toggle="tab">Dates &amp; Price</a></li> </ul> url.py: path('a/', trip.views.tripdetail, name='tripdetail') views.py: def tripdetail(request): Menuz = Tripdetail.objects return render(request,'trip/tripdetail.html') Tabs should be active as it is clicked but its not doing. Its ok with normal in normal HTML codes But Not done in Django -
Python Data frame read json and filter data from dataframe
I have json format like this { "2015": [ { "DayofWeek": 4, "Date": "2015-02-06 00:00:00", "Year": 2015, "y": 43.2, "x": 10.397 } ], "2016": [ { "DayofWeek": 4, "Date": "2016-02-06 00:00:00", "Year": 2016, "y": 43.2, "x": 10.397, "Minute": 0 } ], "2017": [ { "DayofWeek": 4, "Date": "2017-02-06 00:00:00", "Year": 2017, "y": 43.2, "x": 10.397, "Minute": 0 } ] } I am reading JSON file like this, and after reading json file; converting it to data frame with open('sample.json') as json_data: data = json.load(json_data) df=pd.DataFrame([data]) Now, I want filter data based on certain input key value like DayofWeek and Year etc. Example: Case1: if input value is DayofWeek=4, then I want filter all objects having DayofWeek=4. Case2: if input value is both DayofWeek=4 and year=2017, then I want filter all the 2017 years data from json having DayofWeek=4. I have tried this code, but it is not working filteredVal=df['2017'] filter_v={'2015':{'DayofYear':4}} pd.Series(filter_v) -
Python Django Class Syntax Errror
I am relatively new to python and django. Trying to implement a python class but get this strange syntax error from invoice.models import Invoice from invoice.serializers import InvoiceSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class InvoiceList(APIView): def get(self, request, format=None): try: invoices = Invoice.objects.all() serializer = InvoiceSerializer(invoices, many=True) return Response(serializer.data) except Invoice.DoesNotExist: raise Http404 serializer = InvoiceSerializer(invoices, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = InvoiceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST class InvoiceDetail(APIView): def get_object(self, pk): try: return Invoice.objects.get(pk=pk) except Invoice.DoesNotExist: raise Http404 def get(self, request, pk, format=None): invoice=self.get_object(pk) serializer=InvoiceSerializer(invoice) return Response(serializer.data) def put(self, request, pk, format=None): invoice=self.get_object(pk) serializer=InvoiceSerializer(invoice, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): invoice=self.get_object(pk) invoice.delete() return Response(status=status.HTTP_204_NO_CONTENT) this is error I get. I don't understand why it's giving me this error because error seems right to me class InvoiceDetail(APIView): ^ SyntaxError: invalid syntax -
Where to make a loop in templates(index.html) of django?
There are two div for two columns. I want to make a loop in it so that I don't have to repeat. I tried a loop above the section tag then after section tag but it is not working. Instead it shows the picture twice. {% static 'images/fulls' as baseUrl %} {% static 'images/thumbs' as hiUrl %} <section class="thumbnails"> {% for dest in dests %} <div> <a href="{{baseUrl}}/{{dest.img}}"> <img src="{{hiUrl}}/{{dest.img}}" alt="" /> <h3>how are you</h3> </a> </div> <div> <a href="{{baseUrl}}/{{dest.img}}"> <img src="{{hiUrl}}/{{dest.img}}" alt="" /> <h3>Lorem ipsum dolor sit amet</h3> </a> </div> {% endfor %} </section> -
Sort through linked model with ForeignKey
I need to do a sorting of the Credit records through the associated models of CreditPayment. models.py class Credit(models.Model): hot = models.BooleanField(default=False) class CreditPayment(models.Model): credit = models.ForeignKey(Credit) period_to = models.PositiveIntegerField() rate = models.DecimalField(max_digits=7, decimal_places=2) views.py credits = credits.filter(hot=False).distinct().order_by(...) Example of input data: Credit #1: CreditPayment #1: period_to = 12 rate = 10 CreditPayment #2: (minimal) period_to = 10 rate = 8 CreditPayment #3: period_to = 9 rate = 10 Credit #2: CreditPayment #1: (minimal) period_to = 6 rate = 20 CreditPayment #2: period_to = 9 rate = 20 Credit #3: CreditPayment #1: period_to = 12 rate = 8 CreditPayment #2: period_to = 9 rate = 11 CreditPayment #3: (minimal) period_to = 9 rate = 8 As a result, the sample is reduced to: Credit #1: CreditPayment #2: period_to = 10 rate = 8 Credit #2: CreditPayment #1: period_to = 6 rate = 20 Credit #3: CreditPayment #3: period_to = 9 rate = 8 Result: Credit #3 -> Credit #1 -> Credit #2 As you can see, at first the minimum CreditPayment was selected for each Credit (credits at views.py). Then, according to these minimum CreditPayment, allCredit is sorted. If the rate of two or more entries are equal, compare byperiod_to. … -
django: Localhost stopped working suddenly?
I'm truing to run a django server and all of a sudden I'm not able to go to localhost:8000. I was able to a few seconds back, but now now it's just freezing up and saying "waiting for localhost" How do I debug this? -
Sending files as an attachment Django
I have created an XLS file and want to send it as an attachment to an email. The following code is working fine and I receive an email with the XLS file (status code is 200 OK). # This is working code import xlwt import StringIO import zipfile from django.core.mail import EmailMessage work_book = xlwt.Workbook() # Here some boring stuff with excel ... report_name = "do_something_%(username)s_%(current_date)s.xls" f = StringIO.StringIO() work_book.save(f) message = EmailMessage( subject=u"Sample Title", body=u"Sample body", to=["test@company.com"]) message.attach(report_name, f.getvalue()) message.send() But if I try to send compressed XLS file (using zipfile), i don't receive anything (However status code is "200 OK"). I replaced the last 2 lines of code with the following: report_name_zip = 'do_something_%(username)s_%(current_date)s.zip' with zipfile.ZipFile(f, mode='w', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(zinfo_or_arcname=report_name, bytes=f.getvalue()) message.attach(report_name_zip, f.getvalue()) message.send() -
Django serialize one field only instead of whole model in related fields (readonly)
I'd like to serialize a nested model field that only has one field by using the field of the nested model directly. Following code should explain the situation: # models class Tag(models.Model): title = models.CharField(max_length=255, unique=True) class Scene(models.Model): title = models.CharField(max_length=255, unique=True) tags = models.ManyToManyField(Tag, blank=True) # serializers class SceneSerializer(serializers.ModelSerializer): class Meta: model = Scene fields = ('id', 'title', 'tags',) read_only_fields = ('tags',) which outputs the following if used: { "id": 1, "title": "yolol", "tags": [ 1, 2 ] } What I'd like to have is the following output (using Tag.title instead of the primary key): { "id": 1, "title": "A Scene", "tags": [ "3D", "Industry" ] } How do I write a serializer that does this for the tags? -
Manager isn't available; Game is abstract
When i try to save i got this error. Manager isn't available; Game is abstract I tried a few methods I found, but it didn't work; like objects=models.Manager() When i delete objects=models.Manager() i got this error type object 'Game' has no attribute 'objects' my models.py class Game(models.Model): name=models.CharField(max_length=255,blank=True,null=True) slug=models.SlugField(unique=True,max_length=255) match=models.ManyToManyField(Match) objects=models.Manager() def get_unique_slug(self): slug=slugify(self.name.replace('ı','i')) unique_slug=slug counter=1 while Game.objects.filter(slug=unique_slug).exists(): unique_slug='{}-{}'.format(slug,counter) counter+=1 return slug def save(self,*args,**kwargs): self.slug=self.get_unique_slug() return super(Game,self).save(*args,**kwargs) class Meta: abstract = True class LeagueOfLegendsGame(Game): team1player=models.ManyToManyField(Player,related_name='team1player') team2player=models.ManyToManyField(Player,related_name='team2player') -
How to integrate django-pesapal to a subscription site
I am trying to add the process payment function on https://django-pesapal.readthedocs.io/en/latest/ to my signup views for new users to subscribe. How do I go about that and which URL should the signup form have? -
Django Cities Light not populating DB
I'm using django cities light for my app, the first time I installed it and configured it, it worked perfectly. But now after deleting and making changes to my code when I run the commands of Django cities light no data is populated. Though I used the same command an hour ao and it worked perfectly fine. I tried using the force command and all the other options but no results. Here is the link to the lib Django cities light -
relation "background_task" does not exist
I'm trying to run some tasks in the background while running a django server. To do this, I'm using background-tasks library. I've followed the following steps: pip install django-background-tasks Wrote 'background_task', in INSTALLED_APPS in settings.py python manage.py makemigrations background_task the problem arises in the 3rd step giving an error stating: django.db.utils.ProgrammingError: relation "background_task" does not exist LINE 1: INSERT INTO "background_task" ("task_name", "task_params", "... I've tried looking for other solutions but every one of them was the 3rd line. How should I proceed? -
How can I generate Allure report files when working with Django and manage.py test runner?
I have a Django project and I usually run the unit tests with the command: manage.py test I have installed allure-pytest but I don't know how to use it. The documentation is about using pytest, but I don't use pytest to run my tests. Does anyone know how I should run my Django tests and make them generate allure report files, when I use the manage.py test command to run them? -
How to set checkbox on each element of list in Django
I'd like to set a checkbox from Django form on each element of a list in settings but I don't know how to do that. I have this list in settings: COOP_CMS_TEST_EMAILS = [ '"Your name" <coop_cms@mailinator.com>', '"Test Test" <test@test.test>' ] forms.py: class NewsletterHandleRecipients(forms.Form): check = forms.BooleanField() def __init__(self, *args, **kwargs): super(NewsletterHandleRecipients, self).__init__(*args, **kwargs) dests = settings.COOP_CMS_TEST_EMAILS for dest in dests: ... I want to have a checkbox at the left of the string for each element in my list. But I'm blocked, can anyone help me please ? Thanks. -
Django 1.11 showing Warnings message
When I'm running a Django test server locally with ./manage.py runserver, lots of warnings are showing up (DeprecationWarning, RemovedInDjango20Warning), even if they shouldn't be there by default (https://docs.djangoproject.com/en/2.2/releases/1.11/#deprecating-warnings-are-no-longer-loud-by-default). I've put this code in a Django command : import warnings warnings.simplefilter("ignore", DeprecationWarning) warnings.simplefilter("ignore", RemovedInDjango20Warning) and it's hiding the warnings on that command, but I don't know where to put it so that it hide all warnings globally (I've tried in manage.py, settings.py, models.py,...) I've also tried to run python -W ignore manage.py runserver which is supposed to tell python not to show warnings, but it still display a lot of warnings. Warnings look like that : /.../venv/lib64/python3.6/site-packages/review/templatetags/review_tags.py:11: RemovedInDjango20Warning: assignment_tag() is deprecated. Use simple_tag() instead @register.assignment_tag or /.../models/results.py: RemovedInDjango20Warning: on_delete will be a required arg for ForeignKey in Django 2.0. Set it to models.CASCADE on models and in existing migrations if you want to maintain the current default behavior One possibility would be to update Django version and make all change suggested by warnings but it would be too long and I just want to hide those warnings. -
Django does not use variables from local_settings.py
i split my settings file into local_settings (not versioned) and settings (versioned). unfortunately the locally defined variables are not used in a call, although they are successfully overwritten. settings.py MY_GLOBAL = 'i am drawn from the settings.py' try: from .local_settings import * except ImportError: raise Exception('import local_settings.py failed') local_settings.py MY_GLOBAL = 'i am from local_settings.py' in my view i've tried smth like that: show_my_setting.py from my_app import settings print(MY_GLOBAL) I expect "i am from local_settings.py" but get "i am drawn from the settings.py" -
bootstrap django using collapse within a for loop
I'm iterating through the event_list and want to display info for each entry. But my html only shows the first entry despite whatever entry I click on. i.e If i click on green event it expands the my wedding card-body. I want it to expand separate event details for each separate entry. How do I do that? index.html {% extends 'event/eventAdminBase.html' %} {% load static %} {% block content %} {% if event_list %} {% for events in event_list %} <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> Event Name :{{ events.event_name }} </button> </h5> </div> <div id="collapseOne" class="collapse " aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <ul> <li> <p> Event Name :{{ events.event_name }}</p> <p>Venue:${{ events.event_venue }}</p> <p>Type:{{ events.event_type }} </p> <form action="{% url 'event:event-delete' events.id %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-default btn-sm">Delete</button> </form> <form action="{% url 'event:event-update' events.id %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-default btn-sm">Update</button> </form> </li> </ul> </div> </div> </div> </div> {% endfor %} {% else %} <h1>No event entries found on the database.</h1> {% endif %} {% endblock %} -
Django deploy in shared hosting server(Hostgator)
How can i setup my django project into hostgator server which i'm using shared hosting. Is python is setup default or it will need to setup in my server (hostgator server)? Please help me -
Allow all active user to login to django admin site
I am trying to allow all active user to login to admin site because as a default just staff and superusers are able to login to admin site. I've tried to overwrite clean method in my custom crate/change forms but it didn't help # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) @admin.register(User) class UserAdmin(GuardedModelAdminMixin, auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = FIELDSETS list_display = ["username", "name", "is_active", "is_superuser", "is_staff"] search_fields = ["name", "username"] class UserChangeForm(forms.UserChangeForm): class Meta(forms.UserChangeForm.Meta): model = User class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( {"duplicate_username": _("This username has already been taken.")} ) class Meta(forms.UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError(self.error_messages["duplicate_username"])``` -
Django create multiple tables with different name for the same model
I have a system for a network connected vending machine. My team decided to use MySql Master Slave replication to stored the data to the local device. I am trying to find a way to create multiple product tables base on a model with different table name base on the remote device. Eg: remote devide 12 have a seperate table with the name "device_12_product_table" I want to have a way to create a new table when create a new remote device, a way to make GRUD action to a table when i specify a remote machine. Below is the model of my remote machine and the product model class RemoteVendingMachine(models.Model): devicePrivateKey = models.TextField(help_text='RSA private key is big') deviceName = models.CharField(max_length=100, help_text='Device Name') deviceSid = models.CharField(max_length=100) isActive = models.BooleanField(default=True) id = models.AutoField(primary_key=True) product_table_name = models.CharField(max_length=255) def save(self, **kwargs): self.product_table_name = Utils.generate_product_table_name_by_remote_pos(self) class Product(models.Model): productName = models.ForeignKey(ProductName, on_delete=models.CASCADE) price_tag = models.ForeignKey(ProductPrice, on_delete=models.DO_NOTHING, null=True) # A product can be sold at different prices across many machines vendingMachine = models.ForeignKey(RemoteVendingMachine, on_delete=models.CASCADE) # Image should be cache on the client side anyway url = models.CharField(max_length=50, help_text='Product image URL') discountAmount = models.FloatField(default=1) discountExpired = models.DateTimeField(default=None) -
controlling to access files in Django on windows server 2012
i create a website with django 2.2 for sell some files (zip, rar, video , music) and i forced run my website on windows server 2012 , now i want to create a Private link just for a user who buy special files.and user can download that files with private link for 24 hours and Then the private link expires... anonymous user or visitor should not be able to download files or direct access to them !. Just for user who buy them. now How can I implement this scenario with ِDjango? which package in django i need ? or which config i should to do ?? how can i preventing direct access to files? -
get_object_or_404 stops after a single loop
I am trying to extract objects from a model based on another model: Code def financials (request): finance = list(Quiz.objects.filter(owner=request.user.pk).values_list('id', flat=True)) print('finance', finance) invoice_list = [] for i in finance: print('i',i) invoice_object = get_object_or_404(Invoice, invoice_quiz_id=i) invoice_list.append(invoice_object) but it stops after a single loop, any help is appreciated. -
django choose template from admin panel without restarting server
I'm trying to create a website with multiple template for all pages. I've created a templates folder and there are 3 folders in it. each folder contains base.html, home.html, etc. Admin can choose each template from admin panel and in my view load template like this. class HomeView(TemplateView): default_template = CustomTemplate.objects.first().name template_name = default_template + '/home.html' The problem is I have to restart server to apply admin's changes. Is there any way to do this without restarting server? I've also tried to enable / disable loader cache but I guess the problem is not depends to cache system. Any idea would be solution. Thanks in advanced. -
Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['employees\\/edit\\/(?P<pk>[0-9]+)\\/$']
Building an Employee application, After updating an Employee using a form, it just shows this error and the Url seems correct so I can really say where the error is coming from I've crosschecked all my url patterns my views and my url in the form and also tried using the solution in this question, this gives me a bigger error urls.py urlpatterns = [ path('edit/<int:pk>/', views.edit, name = 'edit'), ] views.py @login_required(login_url='/accounts/login') def edit(request, pk): employ = get_object_or_404(Employee, id=pk) logging.info(type(employ)) departments = Department.objects.all() context = { 'employ': employ, 'departments':departments } if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] name = last_name +' '+first_name employee_id = request.POST['employee_id'] email = request.POST['email'] department = Department.objects.get(dept_name = request.POST['department']) address = request.POST['address'] employment_type = request.POST['employment_type'] employment_status = request.POST['employment_status'] role = request.POST['role'] marital_status = request.POST['marital_status'] gender = request.POST['gender'] join_date = request.POST['join_date'] end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date'] location = request.POST['location'] credentials = request.POST['credentials'] passport = request.POST['passport'] hod = request.POST['hod'] phone_number = request.POST['phone_number'] date_of_birth = request.POST['date_of_birth'] date_added = datetime.now() if Employee.objects.filter(employee_id = employee_id).exists() or Employee.objects.filter(email = email).exists(): messages.error(request, 'That ID/Email is Taken') return redirect('edit') else: employee = Employee(first_name='first_name',last_name='last_name',email='email', employee_id='employee_id',department='department',address='address',employment_type='employment_type', employment_status='employment_status',role='role',marital_status='marital_status',gender='gender',join_date='join_date', end_date='end_date',location='location',credentials='credentials',passport='passport',hod='hod', phone_number='phone_number',date_added='date_added',date_of_birth='date_of_birth') employee.save() messages.success(request, 'Employee Created') return redirect('all') return render(request, 'employees/edit.html', context, …