Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Webpack - cannot use url or file loader on development mode
I am using the Django Webpack environment. But I cannot use url() tags that I have defined in css or scss in development environment (eg: app.scss). It works smoothly in production environment. What changes should I make to the webpack config files to fix the problem? Thanks. dev mode prod mode File Tree 📦assets ┣ 📂bundles ┃ ┗ 📂dev ┃ ┃ ┗ 📜stats.json ┣ 📂fonts ┃ ┣ 📜materialdesignicons-webfont.ttf ┃ ┣ 📜materialdesignicons-webfont.woff ┃ ┣ 📜materialdesignicons-webfont.woff2 ┃ ┣ 📜SourceSansPro-Light.ttf ┃ ┣ 📜SourceSansPro-Light.woff ┃ ┗ 📜SourceSansPro-Light.woff2 ┣ 📂imgs ┃ ┗ 📜img.png ┣ 📂js ┃ ┣ 📜app.js ┃ ┗ 📜vendor.js ┣ 📂scss ┃ ┣ 📜app.scss ┃ ┣ 📜style.css ┃ ┗ 📜_variables.scss ┗ 📂staticfiles ┃ ┗ 📂bundles ┃ ┃ ┣ 📂files ┃ ┃ ┃ ┣ 📜img.png ┃ ┃ ┃ ┣ 📜SourceSansPro-Light.ttf ┃ ┃ ┃ ┣ 📜SourceSansPro-Light.woff ┃ ┃ ┃ ┗ 📜SourceSansPro-Light.woff2 ┃ ┃ ┣ 📜app.31d6cfe0d16ae931b73c.js ┃ ┃ ┣ 📜app.8f4d2ea1a4ad26e97c9c.css ┃ ┃ ┣ 📜stats.json ┃ ┃ ┣ 📜vendor.da99f1d241e90357a0d1.js ┃ ┃ ┗ 📜vendor.da99f1d241e90357a0d1.js.LICENSE.txt app.js import '../scss/app.scss' base.html {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example</title> {% render_bundle 'app' 'css' %} </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> … -
Ways to make perfect Django e-commerce website for client?
I need some help regarding Django e-commerce website for a client ,where I want frontend using html/CSS not using react,Vue etc. and CRUD using REST API. Any help will be appreciated. -
How to retrieve all many_to_many relations for each objects in a single query
I have four tables : class Recipe(models.Model): item_recipe = models.OneToOneField(Item, on_delete=models.CASCADE, related_name='item_recipe') items = models.ManyToManyField(Item, through='RecipeItem') class RecipeItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Item(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200, unique=True) effects = ArrayField(models.CharField(max_length=200), blank=True, default=list) pods = models.IntegerField(null=True) level = models.IntegerField(null=True) type = models.CharField(max_length=200, null=True, blank=True, default="Ressource") image = models.URLField() class Prix(models.Model): def __str__(self): return self.item.name prix_x1 = models.IntegerField(null=True) prix_x10 = models.IntegerField(null=True) prix_x100 = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) A recipe is composed of 1 to 8 Items with a certain quantity indicated is the RecipeItem table. I would like a query that gives me the price of every Recipe. In other word, a query that get all items and its prices for every recipe and sum it. I don't find a way to do that without a for loop. -
Django translation: get_language
I set the language with a language chooser like this: def change_lang(request): lang_code = request.GET.get('language') if lang_code: if hasattr(request, 'session'): request.session['django_language'] = lang_code activate(lang_code) return HttpResponse(json.dumps('OK'),content_type=c_type) The page gets reloaded and translated into the chosen language. But when I do another request on the page i.e. to fetch more posts and I want to know the current language and I use lang = get_language() the language is english and not the language that was chosen before. Thank you for any suggestions -
Django - redis Optimisation
I got data from DB using models.objects.all() and saved it in the cache. After a minute or two I just added a large amount of data and want to access them also but they are not getting reflected in the query. How to synchronize cache when new data is added or disable or remove that cache when new data added Don't reply to reduce the time_out want to know cache synchronization as soon as new data added in DB -
django.db.utils.IntegrityError when using raw sql queries in Django
The entire error is django.db.utils.IntegrityError: (1062, "Duplicate entry '6' for key 'auth_user.PRIMARY'") I'm getting this error when using Django to create a sign-up page with raw SQL queries. It comes up when trying to insert values into the 'auth_user' table that is created by Django. The model in question is 'User' from 'django.contrib.auth.models.' and I'm using MySQL as my database management system. Here is the snippet of my view.py: def admin_signup_view(request): form = forms.AdminSigupForm() if request.method == 'POST': form = forms.AdminSigupForm(request.POST) if form.is_valid(): user = form.save() user.set_password(user.password) cursor = connection.cursor() cursor.execute("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'auth_user'") fields = cursor.fetchall() fields_list = [element for tupl in fields for element in tupl] values_list=[] for key,value in user.__dict__.items(): if key in fields_list: if isinstance(value, datetime.datetime): value=value.strftime("'%Y-%m-%d %H:%M:%S'") elif isinstance(value, str): value=str("'{}'".format(value)) elif value is None: value='NULL' values_list.append(value) cursor.execute("INSERT INTO auth_user VALUES (" + ', '.join(str(v) for v in values_list) + ");") return HttpResponseRedirect('adminlogin') return render(request, 'hospital/adminsignup.html', {'form': form}) The issue is caused by cursor.execute("INSERT INTO auth_user VALUES (" + ', '.join(str(v) for v in values_list) + ");") line (i.e 3rd last line). Even though the above error is raised the 'auth_user' table is populated with the data entered in the form … -
How do I create a superuser if I have deployed Django app via git?
So I have an SQLite database in development in the settings.py of the root Django project. settings.py is as follows (regarding databases): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) However, as you can see, my app is up and running on heroku, and the data there is on a PostgreSQL database. My method of deployment to production for this application has been git, and I kind of like the idea of just pushing to github repository and then clicking deploy on heroku. However, I'm quite confused on how to manage this difference in databases. If I were to use heroku-cli, there seem to be a lot of commands to do things with the database, but since I'm just using git I really have no idea how to go about it. Here's a list of equivalent commands I'd like to know how to perform through git: $ heroku run python manage.py createsuperuser $ heroku run python manage.py migrate I have tried doing these on development, migrating there and then pushing to github, but obviously that only changes the SQLite database and does nothing to the production postgresql database. Any idea on … -
Django: How to check if a user has signed up within the last 7 days?
I'm trying to allow users to have access to my app for 7 days after they register with this function: from datetime import datetime, timedelta from django.utils import timezone from django.utils.timezone import localdate class CustomUser(AbstractUser): def free_trial(self): if (self.date_joined - timezone.now()) < timedelta(days=7): return True But testing with accounts made more than 7 days ago i can still see the h1 tag below {% if user.free_trial %} <h1> Your trial has started </h1> {% endif %} -
Django code for adding into db from select
I have found many materials for adding into db from selected item in Select, but I didn't manage to write code for adding from dropdown (select). I wonder if someone has ready solutions for this. here is what I managed to code models.py from django.db import models class Subjects(models.Model): subject = models.CharField(max_length=100) def __str__(self): return self.subject class Meta: verbose_name = 'Subject' verbose_name_plural = 'Subjects' form.py form of ChoiceField from django import forms from .models import Subjects all_subjects = Subjects.objects.all() CHOICES = [('', 'Select Subject')] for s in all_subjects: CHOICES.append(('', s)) class subject_list(forms.Form): sub_list = forms.ChoiceField(choices=CHOICES, label="") views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import subject_list @login_required def directory_page(request): form = subject_list() data = { 'form': form } return render(request, 'directory_page/directory.html', data) With these I only managed to write the ChoiceField fill from database with subjects, and now I need code that will take selected subject's id (it has column id in db table) and Current users id and add them to new database table with columns user_id, subject_id (user_id - current users id, subject_id- selected subjects id) -
Bootstrap Navbar Align Right
I'm trying to align my navbar items to the right in bootstrap. I'd like to have everything aligned right, except for the brand logo. <div class="logo"> <h1><a href="#"><img src="#" alt="" /></a></h1> </div> <nav class="nav-menu d-none d-lg-block"> <ul> <li class="drop-down"><a href="#services"><span>Services</span></a> <ul> <li class="drop-down"><a href="#"><span>Test1</span></a> <ul> <li><a href="#">Test11</a></li> <li><a href="#">Test12</a></li> </ul> </li> <li class="drop-down"><a href="#"><span>Stats</span></a> <ul> <li><a href="#">Stats1</a></li> <li><a href="#">Stats2</a></li> </ul> </li> </ul> </li> <li class="drop-down"><a href="">Support</a> <ul> <li><a href="#">FAQ</a></li> <li><a href="#">Search</a></li> </ul> </li> </ul> </nav><!-- .nav-menu --> -
I want to use abstract model serializer inside another model serializer in django
I used postgres with django. But now I need to use nosql database like mongodb with django. I want to do simple crud operation. I was successful in saving data. But while retrieving data using serializer is not working. serializers.py class LocationSerializer(serializers.Serializer): class Meta: model = Location fields = ['country'] #abstract = True class CustomerSerializer(ModelSerializer): location = LocationSerializer(many=True) class Meta: model = Customer fields = ['name','email','mobileno','location'] -
Making a DRF POST operation work like a Django Admin create object
I am sorry if this question exists elsewhere, but in my search, I did not find anything on StackOverflow or the internet answering my query. I am new to Django Rest Framework. I am working with a MCQ Question Submission model, which records the submission of a quiz as a collection of answers of the examinee to various questions(stored as MCQ Answer model) of a MCQ Quiz( MCQ Quiz model and Choice model). I want to POST the student's name, the quiz name and the Answer Model instances and want to automatically calculate the marks of the student before saving the serializer. Currently, my position is this - If I go the Django Admin and manually create some Answer instances and a Submission instance combining them, then the marks get automatically calculated. But the same doesn't happen while submitting a POST request. Could anyone tell that what is the difference between a POST and an instance creation from Admin? I wish to share the code only if absolutely necessary. -
use os.litdir() in remote script
I have a piece of code using os.listdir() to show the files inside the folder. But I have the error because can´t find the path. I've already verify but is ok. How can I obtain the list with os.listdir() or other method? My piece of code: context['files'] = os.listdir("/static/assets/external_files/"+info_curso.code) -
Problem with database migration from SQLite to Postgres Django
I'm trying to migrate database from sqlite to postgres in django, using this simple method: first, dump data from sqlite python manage.py dumpdata > datadump.json then after connecting to postgres: python3 manage.py migrate --run-syncdb finally: python manage.py loaddata datadump.json and I'm getting error: django.db.utils.ProgrammingError: Problem installing fixture '/home/foka/xx/datadump.json': Could not load advertisements.Package(pk=7): column "days" is of type bigint but expression is of type interval LINE 1: ...ce_currency" = 'PLN', "price" = '12.00', "days" = '7 days 0.... My model looks like this: class Package(models.Model): name = models.CharField(max_length=255, verbose_name=_("name")) price = MoneyField( max_digits=10, decimal_places=2, default_currency="PLN", verbose_name=_("price") ) days = models.DurationField(null=True, blank=True, verbose_name=_("days")) I tried creating new postgres database. In old database I was getting duration days like this: package.days.days but now I'm getting error: Failed lookup for key [days] in 6048000000000000 my question is how can I migrate this field properly?? -
Attach django generated pdf in email
I am building a BlogApp and I am stuck on an Error. When i try to send email with generated pdf then it is sending only the filename. BUT i am trying to send generated pdf in email def send_pdf(request,pk): profiles = get_object_or_404(Profile,pk=pk) sent = False template_path = 'pdf2.html' context = {'profiles': profiles} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # # if downlaod: # # response['Content-Disposition'] = 'attachment; filename="report.pdf"' # # if display: # response['Content-Disposition'] = 'filename="report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response) if request.method == 'POST': form = DownloadDataForm(request.POST) if form.is_valid(): subject = f"{request.user.username}'s download Data" message = response['Content-Disposition'] = 'filename="report.pdf"' send_mail(subject,message,'yawanspace@gmail.com', [request.user.email]) sent = True else: form = DownloadDataForm() context = {'sent':sent,'form':form} return render(request,'download_data.html', context) I am trying to attach file which is in message. ( I don't want to read before send ) I have no idea what i am doing wrong. Any help would be much appreciated. -
How does one best manage database updates with git?
I've looked at the two recommended solutions here and here, but neither addresses this beginner's confusion about how to handle the database file: I push my (tutorial/practice) code to GitHub, and then git pull on PythonAnywhere to deploy it. The file db.sqlite3 was initially included in .gitignore. However, as the tutorial progressed, changes were made to various models, and new migrations were made locally. The new code gets pushed to GitHub again, so the database needs updating. I've re-pushed db.sqlite3 to GitHub, then added db.sqlite3 back to the .gitignore list. But that seems rather inefficient. Is there a better way to handle the db.sqlite3 file between local development and production (though in this case, it's mock production)? Appreciate some enlightenment on this matter. -
Problem with time serieses in django qsstats
I am using qsstats to show plots in my website, but when I try to create time series I get only zeroes. Code of API's method: data = request.query_params orders = Transaction.objects.all() qsstats = QuerySetStats(orders, date_field='date_time', aggregate=models.Sum('cost')) date_dt1 = datetime.strptime(data['start_date'], '%m/%d/%y') date_dt2 = datetime.strptime(data['end_date'], '%m/%d/%y') values = qsstats.time_series(date_dt1, date_dt2, interval=data['interval']) if len(values) > 100: return HttpResponse(json.dumps({'status': 400}), status=400) return HttpResponse(json.dumps(values, indent=4, sort_keys=True, default=str))` Transaction model: class Transaction(models.Model): date_time = models.DateTimeField(default=timezone.now) cost = models.DecimalField(max_digits=15, decimal_places=2) client = models.ForeignKey(Client, on_delete=models.CASCADE) tr_id = models.IntegerField(default=-1) verified = models.BooleanField(default=False) def __str__(self): return str(self.id)` API method returns: `[ "2021-02-10 00:00:00", 0 ], [ "2021-02-11 00:00:00", 0 ], [ "2021-02-12 00:00:00", 0 ], [ "2021-02-13 00:00:00", 0 ], [ "2021-02-14 00:00:00", 0 ], [ "2021-02-15 00:00:00", 0 ], [ "2021-02-16 00:00:00", 0 ], [ "2021-02-17 00:00:00", 0 ], [ "2021-02-18 00:00:00", 0 ], [ "2021-02-19 00:00:00", 0 ], [ "2021-02-20 00:00:00", 0 ],...` Is this a bug or I don't understand something? When I use until_now() it works correct. Are there any other ways to create time serieses in Django? -
Image doesnt upload to specifed folder
I'm creating a blog post app in Django and I want my users to be able to post pictures in their posts.When I try to upload a picture through a form, the picture doesn't get uploaded to rec_pics like i specified in models. My Template {% extends "recepti/base.html"%} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/from-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Add Recipe</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content%} My model class Recept(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset() naslov = models.CharField(max_length=100) sestavine = models.CharField(max_length=100) priprava = models.TextField() rec_img = models.ImageField(upload_to='rec_pics', default='default.jpg') datum = models.DateTimeField(default=timezone.now) avtor = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) likes = models.ManyToManyField( User, related_name="blog_recept", blank=True) favorites = models.ManyToManyField( User, related_name='favorite', default=None, blank=True) newmanager = NewManager() def __str__(self): return self.naslov . . . My views class PostCreateView(LoginRequiredMixin, CreateView): model = Recept fields = ['naslov', 'category', 'sestavine', 'priprava', 'rec_img'] def form_valid(self, form): form.instance.avtor = self.request.user return super().form_valid(form) -
Set permissions for django groups
I am currently trying to set permissions for a django group. I have written a short POSTGRESQL script: INSERT INTO auth_group_permissions (group_id, permission_id) VALUES (2, 1), (2, 2), (2, 4), (2, 5), (2, 6), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13), (2, 14), (2, 16), (2, 21), (2, 22), (2, 24) while group_id is refers to workspace_owner and e.g. permission_id = 1 to overview.add_booking... Now, when I am using the @permission_required(overview.add_booking) it does not reflect those permissions... also if I run user.has_perm('overview.add_booking') i get False. Is someone able to explain me what I am doing wrong? Thank you very much! -
How can I output the data to csv after producing data
Currently, my application is to select the stock data, then analyzing it by using another python script and output the result(in JSON format). Now I would like to add a button to output the result(w_df_split) to CSV, but I am stuck in how to return the output CSV function in this view. views.py: def efficient_frontier_select(request): user_holding = Position.objects.filter(created_by = request.user) selected_stock = None w_df_split = None if request.method == 'POST': selected_stock = request.POST.getlist('stock_symbol') ta, tb, tc = ef.combination_frontier(selected_stock) fy_df, fx_df, w_df, fxfy_df, ef_df = ef.transform_frontier_todf(ta,tb,tc, selected_stock) w_df_split = json.loads(ef.json_format_split(w_df)) context = { 'w_df_split' : w_df_split, } return render(request, 'portfolio/efficient_frontier.html', context) -
Django: can't subtract offset-naive and offset-aware datetimes
i have a 'free_trial' function in my app that allows users who have an account not older than 7 days to try my app. user model class CustomUser(AbstractUser): def free_trial(self): if (self.date_joined - datetime.now()) < timedelta(days=7): return True templates {% if user.free_trial %} #Access Features {% endif %} but i'm getting this error on template can't subtract offset-naive and offset-aware datetimes -
onchange event being triggered when form submits
I would like the user to be able to record an action that they have carried out. I grouped the actions by category and then using two select menus and JS the user is only showed the actions from the category that they have selected. There is also a quantity input that is generated depending on which action is selected. My issue is that when I submit the form, I get the error: Uncaught TypeError: Cannot set property 'onchange' of null The select box and the functionality implemented by the JS work until the form is submitted. index.js document.addEventListener("DOMContentLoaded", () => { // First select let cat_select = document.getElementById("id_post_cat"); cat_select.onchange = () => handleCatChange(cat_select.value); // Second select let desc_select = document.getElementById("id_post_action"); desc_select.onchange = () => handleDescChange(desc_select.value); }); const handleCatChange = (cat) => { let quantity_div = document.getElementById("quantity_div"); quantity_div.innerHTML = ""; // Fetching the actions in the category selected and populating second select fetch(`/action/${cat}`) .then((response) => response.json()) .then((data) => { let desc_select = document.getElementById("id_post_action"); let optionHTML = "<option>---------</option>"; data.actions.forEach((action) => { optionHTML += '<option value"' + action.id + '">' + action.desc + "</option>"; }); desc_select.innerHTML = optionHTML; }) .catch((err) => console.log(err)); }; const handleDescChange = (desc) => { let quantity_div = … -
When is PostgreSQL shared lock released
I am using Django transaction.atomic with a PostgreSQL DB to do a query and then update some data. Like so: with transaction.atomic(): res = my_model.objects.filter(some_filter) DO WORK res.update() If I understand correctly the filter query is creating a shared lock in the PostgreSQL DB. When is that lock released? Directly after its execution or when the entire transaction completes? -
Get available rooms in selected dates django
I am creating a project similar to a house booking system, with a few particularities (you publish the house but you can rent the rooms individually, and you can set when you are on holidays and the house is not available) in Django (rest-framework, so only API for now). The house model can be simplified to: class House(models.Model): title = models.CharField(max_length=127) n_rooms = models.PositiveSmallIntegerField() there is a calendar to save when the house is not available: class Unavailability(models.Model): house = models.ForeignKey(House, on_delete=models.CASCADE, related_name="house_unavailability") unavailable_rooms = models.SmallIntegerField() from_date = models.DateField() to_date = models.DateField() and a model to save when there have been bookings: class Booking(models.Model): house = models.ForeignKey(House, on_delete=models.CASCADE, related_name='booking') booker = models.ForeignKey(UserProfile, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() n_rooms = models.PositiveSmallIntegerField(default=1) rent = models.DecimalField(decimal_places=2, max_digits=8) I am now trying to create an API to search the houses that have at least one room available in the selected dates (not on holidays and not booked). I have seen some similar cases without the particularities I have and using other languages but none using Django (I am using MySQL so I could fall back to SQL if a clean solution with Django does not arise) -
How to specify correctly wsgi for Heroku deploy?
I have following project structure In Procfile i difine web as web: gunicorn george_paintings.wsgi When i deploy project on Heroku i see that Heroku identified my Procfile Starting process with command `gunicorn george_paintings.wsgi` But when i got an error ModuleNotFoundError: No module named 'george_paintings' ` How to properly set up wsgi in Proclife in context of my project structure?