Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a button on django admin main template?
I need a simple way to add a new button on the top of django admin main page. (Black rectangle). It should be like: (Enable site) / (Disable site). Any ideas? Thanks! -
download large pandas data frame as CVS file
I am trying to use this Django reference [Streaming large CSV files][1] [1]: https://docs.djangoproject.com/en/2.2/howto/outputting-csv/#streaming-large-csv-files to download a pandas dataframe as csv file. It requires a generator. # Generate a sequence of rows. The range is based on the maximum number of # rows that can be handled by a single sheet in most spreadsheet # applications. rows = (["Row {}".format(idx), str(idx)] for idx in range(65536)) if I have a dataframe called my_df (with 20 columns, and 10000 rows) .... how do I revise this logic to use my_df instead of generating numbers as in the example. -
Authenticating Access to Django Rest Framework using custom authentication from a Django App
Ive implemented a custom auth system in one(only) Django app on my project Now I want to open my site up to Api access, is there a way to only let users from the Django app access this api. As I don't want to repeat myself (DRY) so was asking if it was possible to work backwards rather than to overwrite the Django rest Authentication with very similar code -
What is the best way to dynamically load a specific app in django depending of another class?
I built a django web app to manage medical datas. I have many specialities using the same project. I'd like to display specific interfaces/forms/templates...depending of the user speciality. I'm on django 1.11 python 3.6. The app is running well. I have patients, and users. Each user have only one speciality (cardiologist, surgeon...), defined by a specific class and linked to the user by a ForeignKey. models.py class Specialite(Auditable): #list of specialites, and link it to user ! id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) spe = models.CharField( max_length = 200, null = False,) #define which app the specialite is linked to... data_app = models.CharField(max_length = 200, null = False, blank = False) def __str__(self): return self.spe class Patient(Auditable): # https://stackoverflow.com/questions/3052975/django-models-avoid-duplicates class Meta: unique_together = ["nom", "prenom", "dob"] MALE = "MALE" FEMALE = "FEMALE" SEXE = ( (MALE, 'Homme'), (FEMALE, 'Femme'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) nom = models.CharField( max_length=50,) nom_naissance = models.CharField( max_length=50,) prenom = models.CharField(max_length=150,) sexe = models.CharField(max_length = 100, choices = SEXE, ) For now, i have one table by patient: first name, last name, dob, weight, height...Only general informations shared by all specialities. I'd like to create specific onetoone tables depending of the speciality to display relevant informations … -
Django Tests: increase testsRun counter
In some Django Tests I have loop to test many things. in the end-result it shows up as: Ran 1 test in 3.456s I would like to increment that counter for each loop, how can I do that? my test looks something like this class MyTestCase(TestCase): pages = ['homepage', 'dashboard', 'profile'] for page in pages: with self.subTest(): # ....testsRun += 1 self.c.login(username='test', password='test') response = self.c.get(reverse_lazy(page)) self.assertEqual(200, response.status_code, msg=page) self.c.logout() response = self.c.get(reverse_lazy(page)) self.assertEqual(302, response.status_code, msg=page) -
SESSION_COOKIE_SECURE=True in Django 2.2 redirects Admin login to itself
I have a simple django 2.2 project that I trying to publish. I am trying to secure the website as best I can. One of the options is SESSION_COOKIE_SECURE. When set to True, my admin pages just won't work. When I go to /admin page, I will see a login. Inputting the correct login and password just brings me back to the exact same page. If I input the wrong login and password, then an error message pops up. So I know I have used the right password. There's nothing special about my admin setup. It's just in the urls.py of the project folder urlpatterns = [ path('admin/', admin.site.urls), ... Of course if I set SESSION_COOKIE_SECURE to False, the admin pages works. I have tried setting the SESSION_COOKIE_DOMAIN to my domain and that doesn't help. What am I missing? Thanks. -
Search an element of the JSONField
I have this Json : { "site-acces": { "title": "digimon", "compare": { "with": "sagromon", } }, "site-denied": { "title": "pokemon", "compare": { "with": "salameche", } } } I would like to do a query in django that do that : search into my Json all object with title that contain "pokemon". I tried that : pokemon.filter(widgets__contains={'title': 'pokemon'}) but it's not working... That return me empty queryset. So i also tried that: base = dashboard.quickreports.filter(widgets__title= 'pokemon') but not working too. I think that not working because the "title" meta is inside the object ... -
Limited editing time for Django model
My model have field with time of creation. How can I allow user to edit item only for 24 hours from created time? Also I want to make an exception from this rule for admin user. -
Changing the output from a text area form based on values from radio buttons in Django - where to start?
I'm pretty new to Django. I have written a text analysis program which I recently managed to deploy online. The program takes a text input and counts the occurrence of words in the input on a corresponding list, and then returns a score on several different variables. I want to improve the program by adding radio buttons which allow the user to compare the text input to a desired score. To exemplify, let's say my categories are "Meat, Fruit, Vegetables, Alcohol". The user provides a list of items from a store, and the program returns a score of how many items belongs to each category. In this example, I want the user to be able to also decide (using radio buttons) if s/he wants a high, medium or low amount of any of those grocery categories. I then want the program to point out any discrepancies in the output. The main problem I'm having is that I don't really know where to start. I've tried searching for many variations of this question, but the answers which show up always include a lot of jargon and/or terminology which I'm not familiar with. Similarly, I tried downloading a quiz app project from … -
Django with redis is caching all pages
I'm using template cache with django-redis and it works properly but, although I don't use decorators (like cache_page, cache_control etc..), django is caching automatically every loaded page. I verified this using redis-cli I tried to use never_cache on every view and it works but I don't see that as a good solution. There's a better way? My configuration is simple CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis_ip:redis_port', 'TIMEOUT': 60 }, } Thanks to all -
Django "Cast" model function error in production environment
I´m deploying my local app to Heroku environment. Everything seems to work fine except one error I get: invalid input syntax for integer: "none" The line that gives the error is the following: total_discount = pedidos.filter(prod_nombre__icontains="PROMO").aggregate(total=Cast(Sum('subtotal'), DecimalField())) This works perfectly in my local environment, so I guess this is a "Cast" model function problem in the production environment, rather than a data related problem. I checked the database has the needed values. I also tryied eliminating that line, so I get an error in the following line, that uses "Cast" also. sub_total_orden = pedidos.aggregate(total=Cast(Sum('subtotal'), DecimalField())) The function is loaded like: from django.db.models.functions import Cast The model class Pedidos(models.Model): productos = models.ForeignKey(ProductosBase, help_text="", blank=True, null=True, on_delete=models.CASCADE) fecha = models.DateField(help_text="", default=datetime.date.today, blank=False, null=True) comprobante = models.CharField(max_length=200, help_text="", blank=False, null=True) cliente = models.ForeignKey(Contactos, help_text="", blank=True, null=True, on_delete=models.CASCADE) vendedor = models.ForeignKey(User, help_text="", blank=True, null=True, on_delete=models.CASCADE) marca = models.ForeignKey(Marcas, help_text="", blank=True, null=True, on_delete=models.CASCADE) categoria_producto = models.ForeignKey(Categorias_Producto, help_text="", blank=True, null=True, on_delete=models.CASCADE) lista = models.CharField(max_length=200, help_text="", blank=True, null=True) prod_codigo = models.CharField(max_length=200, help_text="", blank=False, null=True) prod_nombre = models.CharField(max_length=200, help_text="", blank=False, null=True) uds = models.IntegerField(help_text="", blank=True, null=True) inners = models.IntegerField(help_text="", blank=True, null=True) boxes = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=False, null=True) vu = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=False, null=True) subtotal = models.DecimalField(help_text="", … -
How to create super user in Postgres
I am new to Saleor and I followed all the step in the documentation. However I can't seem to create a new user. I have install PostgreSQL 11 using a .dmg file downloaded from the official website. Every time I run createuser --superuser --pwprompt <username> I get bash: createuser: command not found. If I try to install PostgreSQL with "brew install Postgres" and then run createuser --superuser --pwprompt <username>, I get asked for password twice for the new role then a third time which I have tried to many time to enter with no success. I get the error FATAL: password authentication failed for user <terminal username>. I'm using VS code -
Pagination returns empty QuerySet ( combining multiple models) Django
I'm sending a query result from my database (combining 3 models) to one of my templates, allowing users to filter the output. Displaying all the information I want works just fine, until I try to paginate the results. Then I get empty QuerySet and 'Page 1 of 1' underneath. It completely baffles me as unprocessed set is fetched to the template without any disturbances. Here's my views.py: products =Product.objects.all() out = Sets.objects.filter(ItemInSet__item__name__in=Product.objects.filter(metrics=1).values_list('product_name', flat=True)).exclude(ItemInSet__item__name__in=Product.objects.filter(metrics=0).values_list('product_name', flat=True)).distinct() page = request.GET.get('page', 1) paginator = Paginator(out, 10) # show 10 per page try: out_p = paginator.page(page) except PageNotAnInteger: out_p = paginator.page(1) except EmptyPage: out_p = paginator.page(paginator.num_pages) return render(request, 'item_list.html', {'products': products, 'results': out_p}) And my template: <table id="id_item_list" > {% if results.all %} {% for result in results %} <tr> <form method="GET"> {% csrf_token %} <ul> <a href="/result/{{result.slug}} class="list-group-item list-group-item-action"> <h4>{{ result.name|title }}</h4> <!-- and few more objects from Sets and ItemInSets etc. --> </a> </ul> </form> </tr> {% endfor %} {% else %} <p>No Sets matched your criteria.</p> {% endif %} </table> <div class="pagination"> <span class="step-links"> {% if results.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ results.previous_page_number }}">previous</a> {% endif %} <span class="current">Page {{ results.number }} of {{results.paginator.num_pages }}.</span> {% if results.has_next %} <a href="?page={{ … -
django logout form doesnt appear to be destroying session
I have urls.py: path(r'Logout/',views.Logout), a Logout views.py: def Logout(request): if request.method == "POST": logout(request) return render(request, 'logout_thankyou.html', {}) templates/logout_thankyou.html as: <h1>Log out</h1> <h3>You've been successfully logged out.</h3> Why is this throwing an error of: views.Logout didn't return an HttpResponse object. It returned None instead. What is going wrong here? -
Attribute Error When Using Crispy Forms Filter
I've created a contact form which works fine with no errors. However, when I add a crispy filter to it i get the resulting error: AttributeError at /contact/ - 'str' object has no attribute 'field' forms.py: class ContactForm(forms.Form): your_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) views.py: def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['test@testing.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('contact-us') context = { 'form': form } return render(request, 'main/contact.html', context) template: {% load crispy_forms_tags %} <body> <form method="POST"> {% csrf_token %} {{ form.as_p|crispy}} </form> </body> -
How to display several matplotlib plots in one django template page
I am working on a small app with Django framework. In one of my templates, I have a for loop in which I call an image of a matplotlib plot. But Django is mixing all of my data : some plots charge well, others completly crash and some of them mix the data of two plots. When I charge only one plot, it works fine but the problem occurs randomly when I have two or more plots on the same page. I understand that the problem is due to the simultaneous creation of all plots. Matplotlib is not designed for Django's multi-threading. So, I am looking for a way to create the plots in the right order. Creation of the plot in views.py def GraphsTS(request, h): h = list(map(float, TS.split("-"))) # h is passed as text and transform to a list f = plt.figure(figsize=(5,2)) plt.title('Title') plt.xlabel('Date') plt.ylabel('YLABEL') plt.xticks(rotation='vertical') bar1 = plt.plot(h, color='Green',alpha=0.65) canvas = FigureCanvasAgg(f) response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) matplotlib.pyplot.close(f) return response The for loop in the cluster {% for key, h in dict.items %} <img src="{% url 'GraphsTS' h=h %}"> {% endif %} I expect the plots to be created one after the other. It does not really matter … -
NoReverseMatch at /home/ (Django) [duplicate]
This question already has an answer here: What is a NoReverseMatch error, and how do I fix it? 3 answers Im trying to create a link in my button and I get the following error: Traceback: NoReverseMatch at /home/ Reverse for 'change_friends' with keyword arguments '{'operation': 'remove', 'pk': ''}' not found. 1 pattern(s) tried: ['home/connect/(? P<operation>.+)/(?P<pk>\\d+)/$'] home/urls.py: re_path(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.change_friends, name='change_friends') the button in home.html: <a href="{% url 'home:change_friends' operation='remove' pk=friend.pk %}"> <button type="button" class="btn btn-success">Add Friend</button> Thanks -
How to create a simple visitors' tag using python
I need a clue regarding this task. I was given a project on creating a simple tag to identify visitors within our school premises. It’s like an ID card that displays the names, purpose of visit and the image of the visitor. The image will be captured using a webcam and will be printed along with the visitor’s information. The print will be similar to an ID card and the visitor will use it as a tag when he’s in our school’s premises. Because of my familiarity with python, I chose to use either Django (web platform) of Tkinter (desktop). I’m using OpenCV to capture the image. I’m on the right track? If no, is there any simpler yet a better way of approaching the problem? Thank you. It will appear like this: visitors' tag! -
Group Matching of ids Against a Value
Let's think about it this way. I have a list of donators on the platform alongside a needy. Each of these donators has a wallet with different available_balance. A needy needs $4000, and in these case, no single donator have up to that amount. It's splitted across each donator's wallet. Donator A has $1000 Donator B has $400 Donator C has $300 Donator D has $2000 Donator E has $3000 Now, I want to match donators that can give me the total amount the needy wants to collect. Like a query that will just give me Donator E and Donator A, because the sum of each available_balance gives me the needy's total amount needed. Class DonatorWallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_balance = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0.00')) available_balance = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0.00')) How do I go about cracking up this query? Not necessarily code. Just plain algorithm is better too. -
ModuleNotFoundError When Importing Custom Django App Modules
I'm currently trying to create a custom django app within my project. I'm attempting to access some of the models from another directory within the same project but I am unable to import anything from my app's modules. I've looked into numerous issues here on Stackoverflow and have had no luck with any of them. I've tried editing my sys.path manually. And I've tried messing around with my settings.py file as well. Current Directory: https://gyazo.com/fe75655bd3296c47aaa36f5a10c92dfb I'm trying to run the following import within the bot directory within my titandash application. from titanbot.titandash.models.queue import Queue The fix I tried with my sys.path looks like this: import os import sys cwd = os.getcwd().split("\\") if cwd not in sys.path: sys.path.append("\\".join(cwd)) if cwd[:-1] not in sys.path: sys.path.append("\\".join(cwd[:-1])) sys.path.append("\\".join(cwd + ["titandash"])) I expect for my modules to be importable from either directory back and forth for use in other places. File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\urls.py", line 3, in <module> from .views import dashboard, project_settings File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\views.py", line 3, in <module> from .utils import start File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\utils.py", line 2, in <module> from .models.queue import Queue File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\models\queue.py", line 6, in <module> from titandash.bot.core.bot import grab_functions File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\bot\core\bot.py", line 11, in <module> from titanbot.titandash.models.queue import Queue ModuleNotFoundError: No module named … -
combining Vue js and Django
I have decided to use Vue JS with Django in production mode. I find integrating VueJS with Django through cdn(content delivery network) is easy. Doubt - Will there any performance issue happen with this ? if any, should I use webpack loader -
django DeleteView does'nt redirect to success url after overriding delete function
i have an student model which includes a foreign key of django user model, i want to delete the associated user when user is removed (on delete=CASCADE does vice versa), so i override the delete function put after deletion success_url= '/student/' is not working and url still is e.g. '/students/delete/323/' and keeps the sent pk to url, when i don't override delete function it works like a charm. any idea? class StudentDeleteView(DeleteView): model = Student template_name_suffix = '_confirm_delete' success_url = '/students/' def delete(self, request, *args, **kwargs): related_user = Student.objects.get(student_id=kwargs['pk']).user_id User.objects.filter(id=related_user).delete() return super(StudentDeleteView, self).delete(request, *args, **kwargs) -
Django-datatables-view: How to fix "Uncaught Type Error: $$.each is not a function"
I am trying to use django-datatables-view for one of my models. My browser shows the model fields as columns, and they are rendered like they should be, but there is no data. I get the following error in my browser: [Error] Uncaught TypeError: $$.each is not a function at line 20 URL: http://localhost:8000/static/lineupgenerator/js/datatableview.js I used the datatableview.js file from a reference example app located here: https://github.com/pivotal-energy-solutions/django-datatable-view/tree/master/datatableview/static/js If you click on the datatableview file, you can see where $$.each is used in line 20. I am hesitant to try anything because I am using the datatableview.js file directly from the example app. I am having a hard time determining where my error is located. My model works and I can display data from it without the use of datatableview, so there shouldn't be an issue there. I am new to jquery, Java, et al, so I may be making a simple mistake in that area. #models.py class SourceCSV(models.Model): Position = models.CharField(max_length=100) Name = models.CharField(max_length=100) Player_ID = models.IntegerField() Roster_Position = models.CharField(max_length=100) Salary = models.IntegerField() Game_Info = models.CharField(max_length=100) Team = models.CharField(max_length=100) Site = models.CharField(max_length=100, choices=[('DK', 'DraftKings'), ('FD', 'FanDuel')], blank=True) Sport = models.CharField(max_length=100, choices=[('NFL','NFL'), ('NBA','NBA'), ('MLB','MLB'), ('NHL','NHL')], blank=True) Contest_Type = models.CharField(max_length=100, choices=[('CL', 'Classic'), ('SH', … -
.filter querysets is not displaying data. Django1.11
I tried filtering some data using the .filter and it doesn't display. When I try displaying all of them without filtering, it displays everything...but when I try filtering, nothing works. class Part_Time_DM(models.Model): Location=models.CharField(max_length=15, default="location") def PartFilterView(request): qs = Part_Time_DM.objects.all() location_query= request.GET.get('location') qs = qs.filter(location__icontains=location_query) return render(request, 'home.html', {"qs" : qs}) <!-- Team --> <section id="team" class="pb-5"> <div class="container"> <div class="row"> {% for fulls in qs %} <!-- Team member --> <div class="col-xs-12 col-sm-6 col-md-4"> <div class="card two"> <img src="{{ fulls.Profile_picture.url }}" alt="John" style="width:40%"> <h1>{{fulls.Name}}</h1> <p class="title two">Location : {{fulls.Location}}</p> <br> </div> </div> <!-- ./Team member --> {% endfor %} </div> </div> </section> <!-- Team --> -
Django left join with and condition
I have 3 models Product,Photo,ProductLikeDislike. I am left joining all the three. For that I wrote this query: x=Product.objects.values_list('name','photo','productlikedislike') Through this I am getting correct left join I printed and checked like this: Note: olx is the name of my Django app. print(x.query) SELECT "olx_product"."name", "olx_photo"."id", "olx_productlikedislike"."id" FROM "olx_product" LEFT OUTER JOIN "olx_photo" ON ("olx_product"."id" = "olx_photo"."reference_id_id") LEFT OUTER JOIN "olx_productlikedislike" ON ("olx_product"."id" = "olx_productlikedislike"."product_id_id") ORDER BY "olx_product"."created" DESC Now I want to add extra and condition along with ON statement like this: ON ("olx_product"."id" = "olx_productlikedislike"."product_id_id" and "olx_productlikedislike"."product_liked_by_id"=2) So for this somebody suggested me that use Django's FilteredRelation. I used but it is not adding extra and condition along with ON I used FilteredRelation like this: x=Product.objects.annotate( productlikedislike_product_liked_by_id=FilteredRelation('productlikedislike', condition=Q(productlikedislike__product_liked_by_id=2))).values_list('name', 'photo','productlikedislike') but getting the same sql query no extra and condition. I am using Django 2.1.5