Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access images in my aws s3 bucket in a django html tag?
I'm not very knowledgeable about this topic so I'm going to keep this simple. I set up AWS S3 Storage with Django. When I upload images to one of my models, the image shows up in the appropriate bucket (good). I'm not sure how to access an object inside my storage already. I have an image, say 'apple.jpg' and I want to display it on the website. How do I get this to show? My research says it has to do with AWS_Location but I'm really not sure. Thanks in advance. -
django updating multiple instances with different foreignkey
I'm trying to duplicate multiple data I only need to change their related foreignkeymy problem is that I'm able to duplicate but with the same foreignkey below is my code any suggestions please from django.db import models class Category(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Client(models.Model): cat = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) age = models.IntegerField() married = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.fname + " " + self.lname + " " + str(self.cat) def show_category(request, cat_id): clients = Client.objects.filter(cat__id=cat_id) if request.method =='POST': for i in clients: i.id = None i.cat.id=3 i.save() return redirect('/') context = {'clients':clients} return render(request, 'app/home_cat.html', context) -
Saving API Information Into a Database - Using Django and Fetch API in Javascript
I'm new to APIs with Javascript and Django. I have a project where an API is called in Javascript, and it gets weather information for a specific location (the user types the location into a form first). Currently it does not save the weather info to the database. If the user clicks 'add to favorites' for the location, only then I want to save that info to the database. My question is, would I use a PUT request for this? Also, would I need a totally different fetch request for this, or would I be able to take the one I already have, and just get that data somehow. I'm assuming to save it to the database I would probably need a separate fetch request using PUT, because I only want it to save when the user clicks a button. Here is what I have for the API to get the weather data (this works correctly but this does not save to the database yet). function hi() { function temperature(input) { const myKey = "private"; const api = `https://api.openweathermap.org/data/2.5/weather? q=${input}&lang=en&appid=${myKey}&units=metric`; return fetch(api).then(function(response){ let data = response.json(); console.log(data); return data; }) .catch(error => { console.log('Error:', error); }) } Any guidance is … -
Get username who created/edited record in the Django table
I want to get username who created/edited records and pass this username to template in the table. I have the following code. Any suggestions how can I make this work? Models.py class Employee(ChangeloggableMixin, models.Model): name = models.CharField(max_length = 100) post = models.CharField(max_length = 100, default = '') work_place = models.CharField(max_length = 150, default= '') username = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.name Forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['name', 'post', 'work_place', 'username'] labels = { 'name':'name', 'post':'Post', 'work_place':'Work place', 'username': 'Author of the record', } Views.py def employee_list(request): context = {'employee_list': employees} return render(request, 'employee_register/employee_list.html', context) employee_list.html <table class="hover" id = "myTable" cellpadding="0"> <thead> <tr> <th>Name</th> <th>Post</th> <th>Work place</th> <th>Author of the record</th> </tr> </thead> <tbody id="target"> <tr> {% for employee in employee_list %} </td> <td>{{form.name}}</td> <td>{{form.post}}</td> <td>{{form.work_place}}</td> <td>{{form.username}}</td> </tr> {% endfor %} </tbody> </table> -
"sqlite3.OperationalError: attempt to write a readonly database" even after chmod 777
I' m running a Django application within a docker container. I'm getting this error sqlite3.OperationalError: attempt to write a readonly database. I've tried everything in the Dockerfile RUN chown username db.sqlite3 RUN chmod 777 db.sqlite3 I tried also to run the application as root user, but I still get the same error. -
How to solve pg_dump: aborting because of server version mismatch using docker
I am running a django server(image python:3.8.2-slim-buster) and a postgresql(image postgres:13) database on separate docker containers. I am trying to use django-dbbackup to back up data and ran into this error. # python manage.py dbbackup System check identified some issues: WARNINGS: account.EmailAddress: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the AccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. account.EmailConfirmation: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the AccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. socialaccount.SocialAccount: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SocialAccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. socialaccount.SocialApp: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SocialAccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. socialaccount.SocialToken: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the … -
django framework grpc and http
I have a project. I hope that based on Django framework, HTTP and grpc can be started in one process, and they can share variables. Django grpc framework can start a grpc port, how to open another HTTP port in this project -
how to transform XML file into PDF in python
The data coming from the remote server(Dynamically) in XML format(Response). I want to convert this XML Response into PDF Files. (I am doing manually XML --> HTML --> PDF). Any good approach to make this automatic instead of doing a manual process in python. -
Django Keycloak integration flow
Try to follow the follow steps to integrate keycloak with Django system without using the builtin contrib.auth app. My question is: If I am not using the built-in user objects, how do I determine if a user is authenticated or not, by using the SSO session Keycloak generated? Step 5, associate it with a session, what does it mean? -
how to transform XML to XSL using python
I have a sample XML file like this: <contents> <part title="Lucene Basics(or Fundamentals)"> <chapter title="Lucene Searching"> <section type="internal" title="Lucene Scoring"> <leaf title="How Lucene scoring works" seotitle="how-lucene-scoring-works"> </leaf> </section> <section type="terminal" title="" seotitle=""> <leaf title="hello world" seotitle="how-lucene-scoring-works"> </leaf> </section> </chapter> </part> </contents> Now I want to convert this XML into XSL format in python! any ideas? -
Django: Using a custom user model in django and unable to create a new model object with an associated user instance
I am using a custom user model in django and unable to create() a new object in an associated model that uses User as the unique identifier. I have tried: converting the user model instance to a string using the primary key of the instance (user.id, user.pk). using the commented out get instance of the user object using the user.email attribute Here is my relevant code below! settings.py AUTH_USER_MODEL = 'core.user' Model.py User = settings.AUTH_USER_MODEL def userprofile_receiver(sender, instance, created, *args, **kwargs): if created: breakpoint() #user = User.objects.get(email=instance.email) UserProfile.objects.create(user=instance) post_save.connect(userprofile_receiver, sender=User) class UserManager(BaseUserManager): def create_user(self, email, password1=None, password2=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password1) user.save(using=self._db) return user def create_staffuser(self, email, password1): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password1=password1, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password1=password, ) user.staff = True user.admin = True print("hi") user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, … -
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?