Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-sass-processor won't compile any files
Whenever i run python manage.py compilescss --engine jinja2 this is the result: "Successfully compiled 0 referred SASS/SCSS files." I do have several scss-files that exists and have been changed.python manage.py findstatic example_file.scss finds all the files as well. It seems like the compiler doesn't look through the .jinja2 files even though I have set SASS_TEMPLATE_EXTS = ['.html', '.jinja2'] in base.py. If I run the command with verbose output it only shows that it is parsing files that ends with .py. -
Primary-key collisions in multi-master replication environment using django
I have a multi-master replication setup using Postgres and Bucardo. On top of it, I have a Django application. The setup does not fully works since I keep getting primary-key collisions. Since the replication is configured to clone the whole database, and thus I'm somewhat confident that Postgres' sequence ids are being updated, I wonder if it is not Django that keeps somewhere in memory the last sequential id number. If so, does anyone have any hint on what could be done to fix this issue? Thanks in advance -
Migration error in django, what error am I running into?
I am attempting to migrate my changes with command python manage.py migrate I have already ran the command, python manage.py makemigrations accounts which successfully returns, Migrations for 'accounts': accounts/migrations/0001_initial.py - Create model CustomUser Then in attempting to run python manage.py migrate I recieve this error... Traceback (most recent call last): File "/home/mycroft/C/news/manage.py", line 22, in <module> main() File "/home/mycroft/C/news/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mycroft/.local/share/virtualenvs/news-ToLZWqxe/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mycroft/.local/share/virtualenvs/news-ToLZWqxe/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mycroft/.local/share/virtualenvs/news-ToLZWqxe/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/mycroft/.local/share/virtualenvs/news-ToLZWqxe/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/mycroft/.local/share/virtualenvs/news-ToLZWqxe/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/mycroft/.local/share/virtualenvs/news-ToLZWqxe/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 95, in handle executor.loader.check_consistent_history(connection) File "/home/mycroft/.local/share/virtualenvs/news-ToLZWqxe/lib/python3.9/site-packages/django/db/migrations/loader.py", line 302, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. I am very new to django and can't seem to figure out just what I am doing wrong. Any help would be greatly appreciated! -
Django Redirect Returning 200 But Page Not changing
I've got a form in Django that I submit with code like the following: XHR.open("POST", "/route/to/post/view"); XHR.send(formData); and the route for it looks something like this: def my_view(request): if request.method == "GET": context = {"object": Perso.objects.all()} return render(request, "myview.html", context) elif request.method == "POST": print("post request is", request.POST) print("redirecting...") return redirect("/route/to/another-view") I know that this is working correctly because I get the following output printed when I press the POST button page: post request is <QueryDict: {'csrfmiddlewaretoken': ['6pdzvTNVO8d1KhS9w3IevFGD7w3bprBRQtUaO1TuXDS4RIkTP44IlFdYwJQB7czx'], 'vaccinator': ['tilley evan']}> redirecting... [12/Apr/2021 15:42:34] "POST /route/to/post/view HTTP/1.1" 302 0 [12/Apr/2021 15:42:34] "GET /route/to/another-view HTTP/1.1" 200 3546 and in Chrome I can see that a successful GET request was made, but for some reason the page itself doesn't change. Any advice here? -
Equivalent of query django
How would this sql query be in a django query SELECT DATEDIFF(DAY, [start_date], [end_date] ) days, count(*) FROM [dbo].[purchase.purchase] group by DATEDIFF(DAY, [start_date], [end_date] ) -My model class Purchase(models.Model): name=models.TextField(null=True) end_date= models.DateField(null=True) start_date= models.DateTimeField(auto_now_add=True) -
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)