Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter if month and year between 2 date fields
i have the following models: class Project(models.Model): class Meta: verbose_name_plural = "Projects" verbose_name = "Project" db_table = "projects" employees = models.ManyToManyField(User, related_name="list_employee", blank=True) kickoff_date = models.DateField("start date", null=True, blank=True) close_date = models.DateField("End date(deadline)", null=True, blank=True) # i use default user model from django.contrib.auth.models import User Purpose: I'm trying to find employees that not belong to any projects in each month There are currently 4 users (employees) : root, linh, tu, another Here is the data in table form (trying to populate free row): Currently i have the following code: import time from datetime import datetime a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] x = 12 for n in range(x): a[n] = time.localtime(time.mktime((now.tm_year, now.tm_mon - 2 + n, 3, 0, 0, 0, 0, 0, 0)))[:2] # this return a as list of tuple [(2020, 6), (2020, 7), (2020, 8), (2020, 9), (2020, 10), #(2020, 11), (2020, 12), (2021, 1), (2021, 2), (2021, 3), (2021, 4), (2021, 5)] user = User.objects.all() for i in a: #trying to get all user_id from projects in that month p_list = list(Project.objects.filter(kickoff_date__month__gte=i[1], kickoff_date__year=i[0], close_date__month__lte=i[0],close_date__year__lte=i[0]).values_list('employees', flat=True)) #find users that not in p_list d = user.exclude(id__in=p_list) print(i) print(d) It return the … -
Django- Splitting Tuple to CSV
Trying to export Csv in Django, anyway stuck in split tuple to list So how can i split a tuple to list?? Thanks... -
.env variables not visible inside settings.py file of a Django project run with Docker
I am playing with Docker (deliberately not using docker-compose for now). The problem is that my variable set in .env file is not visible to settings.py, resulting in None being rendered by print(os.environ.get('TEST_VAR')) in settings.py. The problem goes away if I define the TEST_VAR variable inside the Dockerfile. Anyone know what I am doing wrong? Here's how my Django project looks like: Project layout: my_project my_project settings.py .env manage.py requirements.txt Dockerfile Dockerfile: FROM python:3 ENV LANG=C.UTF-8 LC_ALL=C.UTF-8 RUN mkdir /app WORKDIR /app ADD . /app/ RUN apt-get -y update RUN apt-get install -y --fix-missing \ libaio1 \ git \ wget \ curl \ pkg-config \ python3-dev \ software-properties-common \ zip \ && apt-get clean && rm -rf /tmp/* /var/tmp/* RUN pip install --no-cache-dir -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] .env TEST_VAR='wow' The commands I run: docker build -t simple-project . docker run -it -p 8000:8000 simple-project Note that .env is on the same level as settings.py, however I have tried to move it one level up where, say, manage.py is located. -
AttributeError at /orders/ 'QuerySet' object has no attribute 'orderitem
I am working on a django project where I want to display all the orders of a customer. This is my models.py: class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) date_ordered=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=False,null=True,blank=False) transaction_id=models.CharField(max_length=100,null=True) class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True) quantity=models.IntegerField(default=0,null=True,blank=False) date_added=models.DateTimeField(auto_now_add=True) And this is my views.py: def orders(request): customer=request.user.customer order=Order.objects.filter(customer=customer, complete=True) items=order.orderitem.get(order=order) return render(request,"orders.html",{'order':order,}) When I open this template it gives me the error: query set object has no attribute orderitem. I want it to give me the orders for which complete=True and all the orderitems under that particular order so that I can iterate over them and show them in my template but that is not happening for me. PLease help. Any help would be appreciated . -
Django/Pandas: Cannot remove timestamp from pandas.Timestamp
I am trying to remove timestamp and only use Date with pandas.Timestamp but couldn't make it work. I am using Django with Pandas and below is the code: Code: class NumpyEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, pd.Timestamp): return str(obj) return super().default(obj) with pd.ExcelFile(default_storage.open(path)) as xls: sheet_names = xls.sheet_names sheets_df = [pd.read_excel(xls, sheet_name, header=None) for sheet_name in sheet_names] worksheets_columns = [list(sheet_df.columns) for sheet_df in sheets_df] worksheets_data = [json.loads(json.dumps( sheet_df.fillna('').applymap(str).to_numpy(), cls=NumpyEncoder)) for sheet_df in sheets_df] Need to strip if its in excel sheet column with timestamp. Please advise. -
How to have multiple ModelAdmins for same model and a consistent admin url returned by reverse()?
Django 1.11.28 I have multiple admin views for my Car model as described in Multiple ModelAdmins/views for same model in Django admin car/models.py class Car(models.model): ... class ProxySportCar(Car): class Meta: proxy = True class ProxyLuxuryCar(Car): class Meta: proxy = True car/admin.py class CarAdmin(admin.ModelAdmin): ... admin.site.register(Car, CarAdmin) class ProxySportCarAdmin(CarAdmin): model = ProxySportCar ... admin.site.register(ProxySportCar, ProxySportCarAdmin) class ProxyLuxuryCarAdmin(CarAdmin): model = ProxyLuxuryCar ... admin.site.register(ProxyLuxuryCar, ProxyLuxuryCarAdmin) My problem is that when i use reverse, Django will return one random admin path amongst the model and proxy ones. from django.core.urlresolvers import reverse reverse("admin:admin_car", kwargs={"car_id": Car.objects.last().pk}) # Return one of : # u'/admin/car/car/710178/' # u'/admin/car/proxysportcar/710178/' # u'/admin/car/proxyluxurycar/710178/' Is it possible to keep the proxy admin views while having reverse always return the base admin path (ie /admin/car/car/ in my case) ? -
How do I convert a Django session to the new format?
We are using Django 3.0 for our websites (Speedy Net and Speedy Match), and I want to upgrade to Django 3.1 next month. I understand that the sessions format changed in Django 3.1, and that old sessions will be removed in Django 4.0 (see documentation). I want to convert user sessions of users who will visit the site with Django 3.1 and 3.2 to the new session format, before I upgrade eventually to Django 4.0. How do I convert sessions to the new session format? I have to identify that these users are using the old session format, and then convert them (create a new session cookie for them with the new session format). Will it be done automatically by Django, or do I have to do it myself manually? -
How can I make my dynamic sidebar that I have created link to a page that shows the items in that selected group
I have tried a few different loops but they end up showing me all the group names or nothing is shown at all. Any help would be greatly appreciated. I am still fairly new to Django and I believe the reason why I am having this problem is having to do with my Models and view. models.py class Group(models.Model): group = models.CharField(max_length=200, null=True) def __str__(self): return self.group class Publisher(models.Model): publisher = models.CharField(max_length=200, null=True) def __str__(self): return self.publisher class Empowerment(models.Model): title = models.CharField(max_length=200, null=True) group = models.ForeignKey(Group, null=True, on_delete= models.SET_NULL, help_text='select a group for this Empowerment') publisher = models.ForeignKey(Publisher, null=True, on_delete= models.SET_NULL, help_text='select a Publisher for this Empowerment') overview = models.TextField(max_length=1000, help_text='Enter a brief overview of the Empowerment', null=True) problem_to_solve = models.TextField(default='', help_text='Enter the problem this Empowerment helps to solve', null=True) empowerment_benefits = models.TextField(default='', help_text='Enter the benefits of this Empowerment', null=True) empowerment_Image = models.ImageField(default='', upload_to='images/') def __str__(self): return self.title def get_absolute_url(self): return reverse('details', args=[str(self.id)]) def display_overview(self): return ', '.join(overview.name for overview in self.overview.all()[:3]) display_overview.short_description = 'Overview' urls.py urlpatterns = [ path('', views.empowerments), path('details/<int:pk>', views.details, name="details"), path('favorites/', views.favorites), path('downloads/', views.downloads), path('groups_list/<str:pk>', views.groups_list, name="groups_list"), path('publisher_list/<int:pk>', views.publisher_list, name="publisher_list"), ] views.py def empowerments(request): empowerments = Empowerment.objects.all() groups = Group.objects.all() publishers = Publisher.objects.all() empowerment_pages = Empowerment.objects.all() … -
How to: import module from django git project in python script
I have a Django project named backend located on: https://gitlab.company.com/IT/myscompany/backend.git Now, I have a new gitlab project that is a basic python script. Inside the script I want to use some models from the backend django project. How do I correctly import these? What I got now:: import os, sys, django sys.path.append('https://gitlab.company.com/IT/myscompany/backend.git') os.environ['DJANGO_SETTINGS_MODULE'] = 'backend.settings.development' django.setup() got error: ModuleNotFoundError: No module named 'backend' -
how to get the name from <QuerySet [<User: name>]>
I want to keep a list of friends. models.py friends = models.ManyToManyField(User, related_name='friends_list') def __str__(self): return self.friends template {% for friend in friends %} <h2> {{ friend.friends.all }} </h2> {% endfor %} {% endblock %} -
Central Authentication and authorization service
I want to design some "central authentication and authorization service" and I know that there is already a couple. My concerns are not about the standards. In the following lines, I'll try to explain it. I have created two Django client apps that have their own authentication and authorization mechanics. The two applications have different designs thus different permissions and roles. But the users are identical. Now I have to create a third application through which the two former applications have to do authentication and that is OK (using for example OAuth). But the third application is also responsible for authorization, i.e. the roles, permissions (including numerous object-level permissions) are stored by and managed in the third application. The questions are: How can I implement the third application so that it can support non-specific, free-style permissions? How can I store those permissions? How should I transfer the permissions to the client applications? How can I query for some permissions? Should I store all permissions in the third application and query for them each time when I the user asks for some resource, or should I save them locally and update them at some points? I have taken a look at … -
DJANGO - SQL DB - NEW MODEL CLASS DOES NOT FIND PRIMARY KEY
I have a models taked with inspectdb from an sqldb: class Anagrart(models.Model): codart = models.CharField(db_column='CODART',max_length=25, primary_key=True) # Field name made lowercase. fam_mg53 = models.CharField(db_column='FAM', max_length=4, blank=True, null=True) Now I try to call a ForeignKey with this: class ArtList(models.Model): MyArt = models.ForeignKey(Anagrart, on_delete=models.SET_NULL, null=True, blank=True, default=None, related_name='MYART') But when i migrate give me an error: django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]La tabella con riferimenti 'ANAGRART' non contiene chiavi primarie o candidate corrispondenti all'elenco delle colo nne di riferimento nella chiave esterna 'myapp_artlist_MyArt_id_60a12d60_fk_ANAGRART_CODART'. (1776) (SQLExecDirectW); [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Non è stato possibile creare il vincolo o l'indice. Vedere gli errori precedenti. (1750)") what happen? TY -
Template extension renders but not new code
I'm building a Craigslist clone following someone else's work and I'm having trouble extending a template. The template in fact renders but I'm including an h2 text to test it and the only thing that renders is the template itself but not the h2 or anything I try to add to it. Other people that ran into the same issue had, for example, a typo on their urlspattern but mine seems to be correct and also matches the work I'm following. Let me know if there's something else I should share that might help to clarify it. Thanks in advance! Base.html is the template I'm extending and New_search.html is the view I'm trying to extend the template to. This is the code itself: {% extends 'base.html' %} <h2>"NEW SEARCH"</h2> {% block content %} {% endblock content %} my_app/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('new_search', views.new_search, name='new_search'), ] -
Django Multiform validation using Javascript
I have created a two step user registration form which has mainly two fields which need to be validated i.e. the username and the password(password = password confirmation). Both of these fields are in different pages. So is there any way in which I can validate the username and password using javascript when the next button is clicked (i.e. check if the username already exists when the first page's next button is clicked and if password = password confirmation when submit in the second page is clicked) and pass these values to django when submit button at the end of the second page is clicked? -
How to classify an image from Azure Storage in Django using a Tensorflow model
I am developing a django application where the user chooses a machine learning model from a drop down list and uploads an image for classification. This image was initially saved in the project directory (bad, I know) so that I can use it in the classification. Now I save these images in Azure Storage, but at the moment I can't find a way to access them without having to save them locally to classify them, so I think I'll have to temporarily save them in the project directory and once I use them in the ml model, then I remove the images. I would like to deploy this application to Azure web service, so I consider it is a bad idea to save and delete images in the project directory. You can see app's form here models.py image is saved in Azure Storage, the other fields in Azure Database for PostgreSQL. class UploadedImage(models.Model): image = models.ImageField(upload_to='%Y/%m/%d/') uploaded = models.DateTimeField(auto_now_add=False, auto_now=True) title = models.CharField(max_length=50) prediction = models.FloatField(null=True, blank=True) def __str__(self): return self.title forms.py class UploadImageForm(forms.ModelForm): EXTRA_CHOICES = [ ('MOB', 'MobileNetV2'), ('VGG', 'VGG-19'), ('CNN', 'CNN 3BI'), ] predicted_with = forms.ChoiceField(label="Modelo Predictivo", choices=EXTRA_CHOICES, required=True, widget=forms.Select(attrs={'class': 'form-control'}) ) class Meta: model = UploadedImage fields … -
Error: pip installed django but 'django-admin' is not recognized as an internal or external command, operable program or batch file
I am trying to create a file using django-admin startproject sample_project on my command line. I used pip to install Django but for some reason, I keep getting this error: 'django-admin' is not recognized as an internal or external command, operable program or batch file. Django has been installed (I can see the version on the command) but I am specifically having an issue with django-admin. -
Errors when running python3 manage.py syncdb to sync databases in my django application
Hi I am pretty new to django and I ended up with a very big error when I tried running the command python3 manage.py syncdb. I am trying to create a form builder application and encountered the error when I was trying to sync the database with the project. I am using the django-forms-builder from pypi.org. For the error: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/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 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'foo' Any kind of help will be appreciated. -
Django admin interface doesn't perform server side checks to determine validity of csrf token
I've just had some penetration testers decide that my Django admin is potentially exposed to a CSRF attack. Given that I only heard of a CSRF attack when they told me about this, I'm going with this being a configuration issue on my part only I can't seem to find where. Steps to reproduce: Download Burp Suite Community Edition Open Browser (from within Burp Suite) Sign into your Django admin portal Navigate to "Authentication and Authorization" -> "Users" Select a user Modify the first name attribute (do not click save just yet) Turn "Intercept On" within Burp Suite (this will catch the request before it hits your django app) Back within the browser click "Save" Burp suite will catch the request, at this point you should be able to see something like Cookie: csrftoken=HoBcgZfhlb1W5Km3F7NL37BKv9XkNvGYcYSO6h4LzZxF5ceLbShbcmiSl9py9iY2; sessionid=ioo36waf6i7sclcj33stv8lminx3u36e Connection: close csrfmiddlewaretoken=hUR7ZNj0UdeqOBUtoP973QVeQEeHd3KnMu8JP58u81K9O3MbUADxc5CmGEGVzQ2r&username=dev&first_name=tony&last_name=&email=&is_active=on&is_staff=on&is_superuser=on&last_login_0=2020-08-08&last_login_1=09%3A19%3A32&date_joined_0=2020-08-05&date_joined_1=16%3A02%3A29&initial-date_joined_0=2020-08-05&initial-date_joined_1=16%3A02%3A29&_save=Save Change the values within the csrftoken and csrfmiddlewaretoken to something that is 64 char's in length (and match, the values must match) and for good measure change the value of first_name e.g. Cookie: csrftoken=1234567812345678123456781234567812345678123456781234567812345678; sessionid=ioo36waf6i7sclcj33stv8lminx3u36e Connection: close csrfmiddlewaretoken=1234567812345678123456781234567812345678123456781234567812345678&username=dev&first_name=smellysocks&last_name=&email=&is_active=on&is_staff=on&is_superuser=on&last_login_0=2020-08-08&last_login_1=09%3A19%3A32&date_joined_0=2020-08-05&date_joined_1=16%3A02%3A29&initial-date_joined_0=2020-08-05&initial-date_joined_1=16%3A02%3A29&_save=Save Forward the request on to the django server You should see a message within Burp Suite saying "The user was changed successfully." You can … -
How to assign different seller to the same product like amazon?
Here I am building an eCommerce project with python & django. But I am bit confused how to assign different seller to the same product with different prices. Can you please help? -
Decrease the stock quantity after payment made in Django
I am trying to learn Django, and has recently created an e-commerce site, however I have no idea how to decrease the stock quantity of my products once the payment has been made. I am using Paypal as payment method. The main flow is like there is 3 models, Products, OrderItem, and Order. Product has an unique ID. OrderItem will be made once the user added product to cart and proceed to checkout, and product_id will be used as a foreign key. Order will be created and once paypal payment has been made, the order_ordered will be set to true, which mean the order has been made. I am wondering if I can decrease the quantity right after the "order_ordered = true", like "Product.stock_quantity -= OrderItem.quantity", but I don't know how should I get or filter the data I retrieved from database. Help is much appreciated. Product Model (models.py) class Product(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(unique=True) stock_quantity = models.IntegerField(default=0) price = models.IntegerField(default=0) OrderItem Model class OrderItem(models.Model): order = models.ForeignKey( "Order", related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) Order Model user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(blank=True, null=True) ordered = models.BooleanField(default=False) Payment Model … -
Django - How to construct a subquery to go two foreign keys deep?
I've been learning Django recently but I have a complicated situation and I'm not sure what the right subquery should be. Users can post Comments on Posts which belong to Topics. For a particular user, I want to find the Topic they most commented in. Ties can be broken arbitrarily. Here are the relevant portions of the models: class Topic(models.Model): name = models.CharField(max_length=10) title = models.CharField(max_length=10) class Post(models.Model): topic - models.ForeignKey(Topic, on_delete=models.CASCADE) title = models.CharField(max_length=10) class Comments(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=10) User model is the default django.contrib model I'm not sure how to do this in one query? I think I should be able to annotate all Topics based on number of Comments that I filter on user id, and then iterate over those topics to get the max, but that seems inefficent, and I'm not even sure how to write that in Django query form -
I am using cassandra as the database. How can I add TTL to a column in a record in Django with cqlengine?
I dont want to delete the record after TTL but only one field of the record should be set to Null. How can I do this in Django with Cqlengine? -
How can we know if User still active with VUE/Django/JWT?
Currently I use rest_framework_jwt to manage the authentication process, Checked the doc Django REST framework JWT refresh-token I find this sentence below, Each time the user loads the page, you can check if there is an existing non-expired token and if it's close to being expired, refresh it to extend their session. In other words, if a user is actively using your site, they can keep their "session" alive. My query is, How to know user still active? Could we extend this "active" status infinitely? It looks maximum refresh time is: 'JWT_EXPIRATION_DELTA' + 'JWT_REFRESH_EXPIRATION_DELTA' Configuration: Frontend: VUE; Backend: Django; Backend API: DRF -
Getting "Field 'id' expected a number but got 'None'" error while updating an object in django
I want to update an object using UpdateView in django. The update was working until I used inline formset. After using this, the weird problem is happening. views.py: class EmployeeUpdateView(LoginRequiredMixin, UpdateView): """ Update a created a employee """ login_url = '/authentication/login/' template_name = 'employee/employee_update_form.html' form_class = EmployeeAddModelForm # work_form_class = WorkExperienceForm # education_form_class = EducationForm work_formset_class = WorkExperienceFormset education_formset_class = EducationFormset queryset = Employee.objects.all() # Override default get method def get(self, request, *args, **kwargs): id_ = self.kwargs.get("id") employee = Employee.objects.get(id=id_) # work_info = WorkExperience.objects.get(employee=employee) # education_info = Education.objects.get(employee=employee) form = self.form_class(instance=employee) # work_form = self.work_form_class(prefix='work_form', instance=work_info) # education_form = self.education_form_class(prefix='education_form',instance=education_info) work_formset = self.work_formset_class(request.GET or None, instance=employee) education_formset = self.education_formset_class(request.GET or None, instance=employee) print("Employee ID: ", employee) return render(request, self.template_name, { 'form': form, 'work_formset': work_formset, 'education_formset': education_formset, 'supervisor_assigned': employee.supervisor_select } ) # Override default post method def post(self, request, *args, **kwargs): id_ = self.kwargs.get("id") employee = Employee.objects.get(id=id_) # work_info = WorkExperience.objects.get(employee=employee) # education_info = Education.objects.get(employee=employee) form = self.form_class(request.POST, instance=employee) # work_form = self.work_form_class(request.POST, prefix='work_form', instance=work_info) # education_form = self.education_form_class(request.POST, prefix='education_form',instance=education_info) work_formset = self.work_formset_class(request.POST, instance=employee) education_formset = self.education_formset_class(request.POST, instance=employee) # Check form validation if form.is_valid() and work_formset.is_valid() and education_formset.is_valid(): instance = form.save() # Save work experience for work_form in work_formset: work = … -
How to live reload pages in django?
I have tried tjwalch's django-livereload-server but it keeps refreshing the page in a loop which I find kind of annoying. Is there an alternative?