Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple product types in order/product model
I currently have something akin to the following: class ProductOne(Model): # product one specific fields class Order(Model): # order level details (supplier, date, etc ) class ProductOrder(Model): order = models.ForeignKey(WineOrder, on_delete=models.CASCADE) product = models.ForeignKey(ProductOne, related_name="product", on_delete=models.CASCADE) quantity = models.IntegerField("Order Quantity") But now I want to add more Product types (Product2, Product3, etc). Each order can only contain a single product type, but I need the user to select the product type before generating the order for it, and preferably using the standard Admin interface. Does anyone have an opinion about the easiest/cleanest way to achieve this? Cheers -
Docker image from python or linux for django?
I have Django project with postgresql. When dokerize it which base image should I use? FROM alipne:latest(linux) and Install pyenv. FROM PYTHON:tags and use it. -
Django database problem after trying implenet .env
I have a deployed app that I want to make the repository public, for this, I'm using a .env to store my data, but I am having an issue when I make a request do the database, like logging. psycopg2.OperationalError: FATAL: password authentication failed for user "$USER" FATAL: no pg_hba.conf entry for host "FOO", user "$USER", database "FOO", SSL off I runned: pip install django-environ on my setting.py import environ env = environ.Env() environ.Env.read_env() SECRET_KEY = env('SECRET_KEY') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env('NAME'), 'HOST': env('HOST'), 'POST': 5432, 'USER': env('USER'), 'PASSWORD': env('PASSWORD'), } } before that env change, I was able to connect on te site. *DEPLOYED ON HEROKU *I AM RUNNING THE SERVER WITH gunicorn mysite.wsgi -
Django-Shapeshifiter problems
I quite new to django and I'm working in a simple project for the University. I'm trying to use the django-shapeshifter, but just by entering like in the example they provide, I get a syntax error I have one main table connected to tow tables with manytomany relations and would like to work with a single view to deal with the forms. The models: class PreciosUnitarios(models.Model): redimiento = models.ForeignKey(Rendimientos, on_delete=models.CASCADE) mano_obra = models.ManyToManyField(ManoObra, through='PuManoObra') material_id = models.ManyToManyField(Materiales, through='Pu_Material') valor_mo = models.FloatField( validators=[validate_decimals], blank=True, null=True) valor_material = models.FloatField( validators=[validate_decimals], blank=True, null=True) def __str__(self) -> str: return self.redimiento.nombre def get_total(self): return self.valor_mo+self.valor_material def get_absolute_url(self): return reverse('pu_detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): if self.id: pk = self.id v = Variables.objects.get(pk=2) rm = self.redimiento.unidades_jornal jc = ManoObra.objects.get(cargo='Jefe de Cuadrilla') pu_m = Pu_Material.objects.filter(pu_id=pk) pu_mo = PuManoObra.objects.filter(pu_id=pk) tm = pu_m.aggregate(Sum('subtotal'))['subtotal__sum'] tmo = pu_mo.aggregate(Sum('mo_subtotal'))['mo_subtotal__sum'] tmo = (tmo + (((jc.salario*8)/208) * 0.10))/rm total_herramientas = tmo * v.herramientas total_seguridad = tmo * v.seguridad subtotal = tm+tmo+total_herramientas+total_seguridad total = subtotal / (1 - v.gastos_admin) total = total/(1-v.utilidad) total = total*v.iva self.valor_mo = total * \ (tmo/(subtotal)) self.valor_material = total * \ (tm/(subtotal)) super().save(*args, **kwargs) else: super().save(*args, **kwargs) class PuManoObra(models.Model): manoObra_id = models.ForeignKey(ManoObra, on_delete=models.CASCADE) pu_id = models.ForeignKey( PreciosUnitarios, on_delete=models.CASCADE, null=True, … -
Error message: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
I downloaded example code for a Django website. When I ran the server, I encountered the error The SECRET_KEY setting must not be empty. The secret key is set in the settings.py line SECRET_KEY = os.getenv('SECRET_KEY') This Stack Overflow post describes this issue and the accepted answer states that the secret key can be any 50 character string, so I used the same secret key as in another of my projects. SECRET_KEY ='%710m*zic)#0u((qugw#1@e^ty!c)9j04956v@ly(_86n$rg)h' But when I try to run the server using the command python manage.py runserver I get the error message 'This site can’t provide a secure connection. 127.0.0.1 sent an invalid response.' Can someone please help me? Thank you. -
Why does Python's datetime strptime() not set timezone when %Z is specified in a string?
Let's say I have the string: combined_datetime_string = "July 04, 2021 12:00:00 PM MST and I parse it to a datetime object via: dateobj = datetime.strptime(combined_datetime_string, '%B %d, %Y %H:%M:%S %p %Z') Why does Django, then, complain that RuntimeWarning: DateTimeField Task.deadline received a naive datetime (2021-07-04 12:00:00) while time zone support is active? Of course, I could set the timezone manually on the datetime object, but that seems unnecessary. I'd have to extract the MST part (or equivalent) of the string and figure out what timezone object that corresponds to. Shouldn't the %Z part of the original string be able to set the timezone correctly? What am I missing here? -
Login form in django3 using class base view
I've been stuck in a class base login in django...the signup is working however the login is showing the error. Using the URLconf defined in projectname.urls, Django tried these URL patterns, in this order: admin/ [name='homepage'] signup/ [name='signup'] login/ [name='login'] ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ dashboard/ socialcard/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, login/post, didn’t match any of these. URL Pattern path path("signup/", views.SignUp.as_view(), name='signup'), path('login/', auth_views.LoginView.as_view(), name='login'), The View function class SignUp(generic.CreateView): form_class=UserCreationForm success_url=reverse_lazy('socialcard') template_name='registration/signup.html' The settings files. LOGIN_URL='login' LOGIN_REDIRECT_URL='dashboard' LOGOUT_REDIRECT_URL='homepage' The signup model is working however the login model is showing the following error when I submit the form... Here is the form call in the registration folder inside the template where the signup resides. <form action="post"> {% csrf_token %} {{form}} <button type="submit">Login</button> </form> -
Embedding a html document inside of RST
I have a sphynx based website and have specific pages on which i would like to display predefined html files that are stored in a specified directory like _static. In Django it's possible to simply reference the file from the template using an %include tag, does something similar exist for ReStructuredText? I would like to do something like .. title:: Example Page ============= Example Page ============= Introduction to page <insert html part here> Description And after building the website have it combine the html generated from RST and the html file specified. -
Saving File in Model in View works but not in Celery Task
I experience this very strang behaviour that when I save a new model instance in my view, the assigned File gets saved, but when I do so in Celery, the instance gets saved, but not the file. Those is are my views (shortened): def post(self, request, *args, **kwargs): [...] html = render_to_string('pdf/w_html.html', {'request': self.object}) out = BytesIO() HTML(string=html).write_pdf(out, stylesheets=[CSS(settings.STATIC_ROOT + "/css/pdf.css"), 'https://fonts.googleapis.com/css2?family=Montserrat&family=Playfair+Display&display=swap']) document = Document(product=product, document_type=4, language=1, date=timezone.now().date(), file=File(out, name='Best_Execution_Report.pdf')) document.save() Where self.object is a Request instance. The above code does exactly what it should (ie saving the model and the generated pdf). But as soon as I modify the above code like this: def post(self, request, *args, **kwargs): [...] generate_best_execution_report.apply_async(kwargs={'request_id': self.object.pk}) with the following celery task: @shared_task def generate_best_execution_report(request_id): """Task to automatically generate best execution Reports and save it to the Documents Model (of the product app).""" request_obj = Request.objects.get(pk=request_id) logger.info(request_obj) html = render_to_string('pdf/w_html.html', {'request': request_obj}) logger.info(html) out = BytesIO() HTML(string=html).write_pdf(out, stylesheets=[ CSS(settings.STATIC_ROOT + "/css/pdf.css"), 'https://fonts.googleapis.com/css2?family=Montserrat&family=Playfair+Display&display=swap' ] ) logger.info(out) with transaction.atomic(): document = Document(product=request_obj.product, document_type=4, language=1, date=timezone.now().date(), file=File(out, name='Best_Execution_Report.pdf')) try: document.save() except Exception as e: logger.info(e) logger.info(document) return True (please note that request is a one-to-one relation on product, so I have to slightly change how the Document instance … -
Create nested form handling many to many relation
I have the model structure like below: class Survey(models.Model): name = models.CharField(max_length=64, unique=True) class Meta: permissions = ( ( "view_stats", _("Can see statistics on surveys"), ), ) class Question(models.Model): text = models.CharField(max_length=64, unique=True) multiple_choice = models.BooleanField( default=False, null=False, verbose_name=_("Multiple choice") ) respondents_particulars = models.BooleanField( default=False, null=False, verbose_name=_("Respondents particulars") ) class SurveyQuestion(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) class Answer(models.Model): text = models.CharField(max_length=16, unique=True) class QuestionAnswer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) I don't use ManyToManyField to avoid problems of desynchronization of relation answer to question as the answer can be part of multiple questions at once but it's not the point of the question. Now, based on the structure, I want to simplify the way surveys are added. In the admin I have to create survey object, then some questions, connect them using SurveyQuestion, add answers for questions and connect them in the same way. How to create the form which would offer me creating survey with possibility of choosing questions for the survey of existing ones and adding (multiple) new questions for the survey with existing answers, new answers or both at once. I suppose I should use ModelForms as well as formsets but I … -
display unique constraints errors message in html template dango
i'm trying to show unique constraints error in the template but i dont know to call back the error i know this works {{form.errors}} but it display the entire error messages in one place class A(models.Model): name = models.CharField() dob = models.DateTimeField() class Meta: constraints = [ models.UniqueConstraint(fields=['dob','name'],name=_('full_information')) ] for the other fields i use this in my template {% if form.name.errors %} {{form.name.errors}} {% endif %} but i dont know what should i do for the full_information error message ? thank you ... -
Standard way to transform view API to celery tasks
I have this in my admin.py: # function to upload the data def upload_data(self, request): # if the request from the form is a post method if request.method == 'POST': # get the file data_file = request.FILES["data_upload"] # get current active tab active_sheet = load_workbook(data_file).active try: # only save if not the first field. first field is reserved for the labels for row in range(2,active_sheet.max_row + 1): # save the new user into the user model new_user = get_user_model().objects.update_or_create( username = active_sheet["{}{}".format("A", row)].value, email = active_sheet["{}{}".format("B", row)].value, ) # return to admin/url url = reverse('admin:index') + 'url' return HttpResponseRedirect(url) except Exception as e: logger.error(e) form = DataImportForm() data = {"form": form} return render(request, 'admin/custom_bulk_upload.html', data) which is a simple form for bulk uploading data. It's good on my localhost, but the server is returning a 502 Bad Gateway Reply. On nginx error log I see this: upstream prematurely closed connection while reading response header from upstream I understand it's because of very large data being attempted to upload from the excel file. How may I resolve this issue? -
How to display the user ID in a Django table
I am creating a site with a Forum type of format, where users can create Posts-- where they make statements or ask questions, etc. Then under the Posts, other users can create comments to this Post and carry on the discussion, or whatever the case may be. The problem I'm having is when it comes to creating pages that show all the Posts, according to the User that created them. I will show you the code that I have below: the second link with the tags is not linking me to the Posts created by that particular user, but always shows the same content from User #1 (the admin user). Can you tell me what I'm doing wrong that doesn't allow this to work? Thanks. {% for post in posts %} <tr> <td>{{ post.postTitle }}</td> <td>{{ post.postBody }}</td> <td>{{ post.user }}</td> <td><a href="{% url 'single_post' post.id %}" class="btn btn-info">View Post</a></td> <td><a href="{% url 'user_post' user.id %}" class="btn btn-info">User's Posts</a></td> </tr> {% endfor %} Example of Posts page -
Django OAuth Toolkit - Only admin users issue
I'm implementing OAuth in my Django Rest Framework backend with Django OAuth Toolkit so I can grant access (via authorization code) to Google Actions so when my users trigger an action, my backend can search the user resources and send a specific MQTT message. I have already set up the flow correctly, but the problem I'm facing is that when the authentication form is presented by Django OAuth Toolkit, it only allows my admin users to log in. How can I give any user in my DB the possibility to retrieve an access token? -
Easiest way to display Django model data in html
I have data being stored in a Django model, and I want to display that data in my HTML file. What is the easiest way that I could do this? I am familiar with this question, but it does not help me because it is not very detailed and does not have a definite answer. Can someone please help me? My code is down below. Django Model: class userdetails(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) HTML where I want to display data from the model: <div class="box"> <span class="value"> </span> <span class="parameter">Points</span> </div> -
Django User Editing, AbstractUser
We are trying to build endpoints to allow users to edit their own profiles from our front end and we've encountered a problem while trying to edit the "logged in user". This issue happens in django admin as well. For example in django admin: if we have 3 users, (imagine all three are super users/is_staff for now). Logged in user 1, I can edit users 2 and 3, but when I go to edit user 1 (logged in user), the message says it was updated but the database does not change. If I then login as user 2 and update user 1, I can update user 1 but not user 2 as the logged in user. This same behavior happens on our endpoints with request.user. request.user can edit any user except for the logged in user. Background We do use a custom user model: class User(AbstractUser): timezone = models.CharField(max_length=255, blank=True, null=True) is_customer = models.BooleanField(default=False) is_agent = models.BooleanField(default=False) is_carrier = models.BooleanField(default=False) is_shipper = models.BooleanField(default=False) is_tracking = models.BooleanField(default=False) class Meta: db_table = 'auth_user' def __str__(self): return self.first_name It is defined in settings: AUTH_USER_MODEL = 'accounts.User' It's likely that when we added the custom user model we did something wrong as I believe … -
How can I post multiple object with form data via django rest framework
class DeliveryCompany(models.Model): CompanyName = models.CharField("CRegNo", max_length=50, default=None, null=True, blank=True) Address = models.CharField("CName", max_length=100, default=None, null=True, blank=True) CompanyLogo = models.ImageField( default=None, null=True, blank=True) class DeliveryRoute(models.Model): Delivery = models.ForeignKey(DeliveryCompany, on_delete=models.CASCADE, default=None, null=True) RouteFrom = models.CharField("RouteFrom", max_length=100, default=None, null=True, blank=True) RouteTo = models.CharField("RouteTo", max_length=100, default=None, null=True, blank=True) One company delivers multiple routes. How can I post the data via DRF? Kindly help. Note:- There is an ImageField in DeliveryCompany -
"user" is not set when parsing a data-dict to a Django form, but all other fields are
Say I have the following #models.py class MyModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) link = models.URLField(max_length=2048) date_added = models.DateTimeField(default = timezone.now) used = models.BooleanField(default = True) and my form class MyModelForm(forms.ModelForm): class Meta: model = Wishlist exclude = [ "user","date_added" ] If I try to create an instance like (note, I have omitted the if request.method="POST" etc. for clarity) def myView(request): user = request.user instance = MyModel(user=user) data = {"link":link,"date_added":domain,"user":user} form = MyModelForm(data=data) form.save() the link and date_added is written to the database, but the user field is empty. If I set the user to the instance after the form is created like def myView(request): user = request.user instance = MyModel(user=user) data = {"link":link,"date_added":domain} form = MyModelForm(data=data) form.save(commit=False) form.instance.user = user #Setting the user here form.save() It works like a charm. How come, I cannot set the user in the data-dict, and is there a way to do so? -
Incorrect username and password for Custom User model
I have created a custom user model models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("Wrong!") if not username: raise ValueError("Wrong!") user = self.model( username =username, email = self.normalize_email(email), ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, username, email, password): user = self.create_user( username = username, email = self.normalize_email(email), password = password ) user.is_superuser = True user.is_admin = True user.is_staff = True print(user, self.normalize_email(email), password) user.save(using = self._db) return user class Account(AbstractBaseUser): username = models.CharField(max_length=15, unique=True) email = models.EmailField(max_length=60, verbose_name='email address', unique=True) address = models.CharField(max_length=200, null=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Even did the proper setting in the admin.py files: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Account # Register your models here. class AccountAdmin(UserAdmin): list_display = ['username', 'email', 'address'] search_fields = ['username', 'email'] readonly_fields = ['address'] filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) But the admin panel tells me the username … -
How to achieve custom sorting in django?
From the below model I need the last 3 days comment sorted by likes and again the next 3 days comments sorted by likes and again the next three days sorted by likes... goes on for example today is 24th June I need comments from 24,23,22 sorted by number of likes + comments from 21,20,19 sorted by likes+ comments from 18,17,16 sorted by likes so on ........ how to achieve it class Posts(models.Model): comment_text= models.CharField(max_length=1000) date = models.DateTimeField(default=timezone.now()) likes = models.IntegerField(default=0) -
Django migration fails with InvalidForeignKey: "unique constraint" error for "django_site"
I've run into a django migration problem. Please help if you have any idea how to get around this! I upgraded Django from 2.2.7 to 3.2. In the new system I continued work, adding a number of new models. I added a new model called "Space" which has a one-to-one relationship with the Django Site model. This all worked on my development machine (PostgreSQL 9.6) and staging machine (PostgreSQL 9.4, although I had to work around a minor incompatibility with Django 3.2). However, on production we have upgraded from an old version of PostgreSQL 9.4, to PostreSQL 12. Now the migration won't run! It gives the following error: Running migrations: Applying appname.0039_auto_20210521_1034...Traceback (most recent call last): File "/data/virtualenvs/appname/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "django_site" This is the part of the migration file 0039_auto_20210521_1034 that must be causing the problem...? migrations.CreateModel( name='Space', fields=[ ('site', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='spaces', serialize=False, to='sites.Site', verbose_name='site')), ('virtual', models.BooleanField(blank=True, default=False)), ], ), The model looks like this: class Space(models.Model): """Space model is OneToOne related to Site model.""" site = models.OneToOneField( Site, on_delete=models.CASCADE, primary_key=True, related_name='space', verbose_name='site') virtual = models.BooleanField(null=False, blank=True, default=False, help_text="The kind of space … -
Load Static doesn't work when I try to implement Bootstrap theme with Django
So I downloaded a bootstrap theme called "modern-business" and I tried to merge it with my django app. This is how it looks: How it looks This is how it should look: How it should look I was able to figure out that my load static isn't working, because I tried to display some pictures on the webpage and I was able to do that when they were in the same folder as index.hmtl file. But they did not work when I put the images in the static file. This is how I am writing it. for the css, images and the js src lines link href="{% static 'css/styles.css' %}" rel="stylesheet" I have included {% load static %} as well My static file is in /mainproject/recordmgmt/static This is my first time trying to merge django and bootstrap and also the first time using django. I think there I am making a mistake with adding the correct path,but I could be wrong. Let me know how to fix this. -
Django exclude query, can i pass multiple parameters?
I have a query and i want to exclude null companies as well as specific user email. Demo.objects.all().exclude(company__isnull=True, email="abc@gmail.com") but seems like above exclude does not work with multiple arguments, my return queryset has email="abc@gmail.com" in it. If i try above query with single arguments, it works. but not working with multiple arguments. Anyone has any idea how to pass multiple arguments in django exclude ? Thanks -
list index out of range in python django
I've creating an application of books recommandation using python in django , so i'm trying to applicate the k means algorithm of machine learning but when i run it i had an IndexError at /log_in/ list index out of range "in the last line of code",here is the code: # Save session as cookie to login the user login(request, user) # get request user reviewed books user_reviews = BxBookRatings.objects.filter(id=request.user.id) user_reviews_books_ids = set(map(lambda x: x.isbn, user_reviews)) #create matrix all_user_names = map(lambda x: x.username, BxUsers.objects.only("username")) all_books_ids = set(map(lambda x: x.books_id, BxBooks.objects.only("books_id"))) num_users = len(list(all_user_names)) ratings_m = dok_matrix((num_users,max(all_books_ids)+1),dtype=np.float32) all_user_names1= list(all_user_names) for i in all_user_names: # each user corresponds to a row, in the order of all_user_names user_reviews = BxUsers.objects.filter(username= all_user_names1[i]) for user_review in user_reviews: ratings_m[i,user_review.books_id] = user_review.book_rating # Perform kmeans clustering # k = int(num_users / 10) + 2 k=4 kmeans = KMeans(n_clusters=k) clustering = kmeans.fit(ratings_m.tocsr()) Cluster.objects.all().delete() new_clusters = {i: Cluster(name=i) for i in range(k) } for cluster in new_clusters.values(): # clusters need to be saved before referring to users cluster.save() for i,cluster_label in enumerate(clustering.labels_): new_clusters[cluster_label].users.add(BxUsers.objects.get(username=all_user_names1[i])) thank you for helping me to solve this problem -
Django template filter extract from list
My view context dictionary produces a list of footage numbers (eg. [1200, 1137, 1428, 5774... ]). I have corresponding tags in my template that pull specific list members... <td> {{ footage | slice:"-1:" }}</td><td> {{ footage | slice:"-2:-1" }}</td><td> {{ footage | slice:"-3:-2" }}</td><td> {{ footage | slice:"-4:-3" }}</td> problem is – when rendered, the html displays the values as a list with a single value – as opposed to a standalone string... how can I extract the values from the brackets (pull them from the lists)?