Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to upload multiple images for one product without creating another table for images
I want to store images path in single field "like store them in JSON field {'image1','image2'}" and then display the images in a slider. I'm using Angular 11 and Django. -
Ordering related model values in django-rest admin view
I want to see this view with the features list sorted alphabetically. The model from the view above comes from is AircraftModel. models.py: class AircraftModelFeature(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class AircraftModel(models.Model): features_list = models.ManyToManyField(AircraftModelFeature) # ... other stuff ... def __str__(self): return self.name serializers.py class AircraftModelFeatureSerializer(serializers.ModelSerializer): class Meta: model = AircraftModelFeature fields = "__all__" class AircraftModelSerializer(serializers.ModelSerializer): features_list = AircraftModelFeatureSerializer(many=True, read_only=True) # ...other stuff... class Meta: model = AircraftModel fields = ['id', 'features_list',] # there are more fields, omitted views.py class AircraftModelFeatureViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = [IsAdminOrReadOnly] queryset = AircraftModelFeature.objects.all().order_by('name') serializer_class = AircraftModelFeatureSerializer class AircraftModelViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = [IsAdminOrReadOnly] queryset = AircraftModel.objects.all().order_by('name') serializer_class = AircraftModelSerializer So, how can I make that list sorted? -
set env variable from a Makefile command and use in another Make command
I'm trying to connect to the Google Cloud SQL DB instance from my local machine inside a Django project. As you might know, we can create management commands in Django. So I created two management commands which basically does some ETL stuff. To make my life simple, I actually created commands in Makefile for these mgmt commands. mgmt_cmd_1: $(eval DB_HOST := $(gcloud sql instances describe <GCP_DB_INSTANCE> --project <GCP_PROJECT_ID> --format="value(ipAddresses.ipAddress)")) DB_HOST=$(DB_HOST) python manage.py mgmt_cmd_1 mgmt_cmd_2: $(eval DB_HOST := $(gcloud sql instances describe <GCP_DB_INSTANCE> --project <GCP_PROJECT_ID> --format="value(ipAddresses.ipAddress)")) DB_HOST=$(DB_HOST) python manage.py mgmt_cmd_2 Now as you can see some part(1st line) is duplicate. in both above commands. I want to get rid of that duplicacy. I want something like below so that I can reuse even if in future I have more than 2 mgmt commands. get_db_host_ip: $(eval DB_HOST := $(gcloud sql instances describe <GCP_DB_INSTANCE> --project <GCP_PROJECT_ID> --format="value(ipAddresses.ipAddress)")) mgmt_cmd_1: DB_HOST=$(DB_HOST) python manage.py mgmt_cmd_1 mgmt_cmd_2: DB_HOST=$(DB_HOST) python manage.py mgmt_cmd_2 I guess probably I can wrap these two commands and create another Make command, like below. but not sure if that always works. mgmt_cmd: @$(MAKE) get_db_host_ip @$(MAKE) mgmt_cmd_1 So I'm wondering if there is even a better way to do this? maybe using some kind of … -
responsive img for site [closed]
I have a board that I want to stay together like this photo But when the page shrinks a bit, the two images are broken and placed at the bottom of each other like a yen. I want the photos to make themselves smaller when the screen gets smaller. Thank you for your help -
How to export and migrate OpenSlides database?
I encountered an error message while exporting my OpenSlides database. My goal is to switch from a SQLite database to PostgreSQL database in OpenSlides, but unfortunately, as I said, exporting doesn't quite work. Can someone help me please? Error Message: ModuleNotFoundError: No module named 'settings' -
How to create a chart of total number of analyzes made in months?
I created a customer management system with Django. Every user has several customers and every customer has several reports. Users make analyses of these reports and send them to a user. This process is ApprovalProcess. I have an ApprovalProcess model and I want to create a line chart that shows the total number of analyzes made in months during the year. (By using begin_date) How can I do that? models.py class ApprovalProcess(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='starter') doc_id = models.ForeignKey(Pdf, on_delete=models.CASCADE, null=True) begin_date = models.DateTimeField(null=True) ... views.py def approval_context_processor(request): all_approvals = ApprovalProcess.objects.filter(user_id__company=request.user.company) ... dashboard.html ... <div class="chart-container" style="min-height: 375px"> <canvas id="statisticsChart" ></canvas> </div> <script> var ctx = document.getElementById('statisticsChart').getContext('2d'); var statisticsChart = new Chart(ctx, { type: 'line', data: { labels: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], datasets: [ { label: "# of Approval", borderColor: '#54bbf3', pointBackgroundColor: 'rgb(84,187,243, 0.6)', pointRadius: 0, backgroundColor: 'rgba(84,187,243, 0.4)', legendColor: '#f3545d', fill: false, borderWidth: 1, data: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], }, ] }, options : { responsive: true, maintainAspectRatio: false, legend: { display: true }, tooltips: { bodySpacing: 5, mode:"nearest", intersect: 0, position:"nearest", xPadding:20, yPadding:20, caretPadding:10 }, layout:{ padding:{left:5,right:5,top:15,bottom:15} }, scales: { yAxes: [{ ticks: { fontStyle: "500", beginAtZero: true, maxTicksLimit: 5, padding: 10 }, gridLines: { drawTicks: false, display: false … -
How to use a for loop in multiple Orderdict in django rest framework?
I have to run a for loop to update the certain fields of a model. The validated_data that I have is a list of Orderdict which is as follows: [OrderedDict([('id', 340), ('order', <Order: mylo@gmail.com>), ('item', <Product: AaaAAAAUpdatedpicturetest>), ('order_variants', <Variants: AgainTest>), ('quantity', 5), ('order_item_status', 'Cancelled')]), OrderedDict([('id', 339), ('order', <Order: mylo@gmail.com>), ('item', <Product: Kiara Terrell>), ('order_variants', <Variants: OAXWadRTZ_12C>), ('quantity', 3), ('order_item_status', 'To_Ship')])] The code I have used is as follows, but the fields inside the model are not updated although it is not throwing any error. class OrderUpdateSerializer(serializers.ModelSerializer): order_items = OrderItemUpdateSerializer(many=True) billing_details = BillingDetailsSerializer() class Meta: model = Order fields = ['id','ordered','order_status','order_items','total_price','billing_details'] def update(self, instance, validated_data): instance.order_status = validated_data.get('order_status') instance.ordered = validated_data.get('ordered') #billing_details_logic billing_details_data = validated_data.pop('billing_details',None) if billing_details_data is not None: instance.billing_details.address = billing_details_data['address'] instance.billing_details.save() #order_items_logic instance.save() #instance.order_items.clear() order_items_data = validated_data.pop('order_items') print(order_items_data) #The logic I have written is here. for order_item_data in order_items_data: oi, created = OrderItem.objects.update_or_create( id = order_item_data['id'], defaults={ # 'quantity' : order_item_data['quantity'], 'order_item_status': order_item_data['order_item_status'] # } ) instance.save() return super().update(instance,validated_data) -
How to pop None from serializer.data in python?
When i looping through serializer.data is shows None inside that. I want to pop None from that. If I have: serializer.data = OrderedDict([('customer', OrderedDict([('name', 'Sachin'), ('email', 'abc@gmail.com'), ('created_at','2021-03-12T15:04:25.695147+05:30'), ('updated_at','2021-03-12T15:04:25.695147+05:30'), ('user', 9)]))]) None OrderedDict([('customer', OrderedDict([('name', 'Sachin'), ('email', 'abc@gmail.com'), ('created_at', '2021-03-12T15:04:25.695147+05:30'), ('updated_at', '2021-03-12T15:04:25.695147+05:30'), ('user', 9)]))]) -
I can't find the GitHub API for extract the code of a repository .{please help}
I am working with GitHub API. But I don't find any API that will help me to see and extract the different version of code. Please help me. I use these two API for show the repository and search users. "user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}", "user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}" Please help me to find the GitHub API. -
CustomUser relation doesn't exist : Django migration error
I'm quite new to Django and ran into a problem while trying to create a custom user. I followed all the steps outlined to create one, but because I initially started out with the default User model I deleted all my migrations and my postgres db to start from scratch (if not, I read it would cause problems). makemigrations works fine, but then when I want to migrate I get the following error: django.db.utils.ProgrammingError: relation "cyclabApp_customuser" does not exist. Applying admin.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "cyclabApp_customuser" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards … -
Django, makemigrations doesn't detect model changes
I am learning Django and I am using this tutorial: https://www.youtube.com/watch?v=F5mRW0jo-U4&t=912s I created an app called products and I have it in installed_apps. Upon creating a Products class in the models.py file in the products app folder, I created some properties such as price. However, when I tried to use the makemigrations command, no changes detected was reported. Folder Layout and Settings Models.py I checked if there were any issues with the Products class but there doesn't seem to be any as far as I can see, so I am at a loss as to why no changes were detected. -
Can I send requests to the server from HTML in email?
I am trying to implement the following functionality. The server sends an email to a user who doesn't necessarily have an account in the server. In the email, the user is asked to rate a certain model (send a request to the server). Can I make it in such a way that the user can click the button and doesn't get redirected to some other page, but sends the request directly to the server. I am using django. -
Django - crispy form not showing
I'm trying to render this form: class LoadForm(forms.Form): class Meta: model = Load def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( 'whouse', 'supplier', 'company', 'product', 'quantity', 'unit_price', 'load_date', ) ) with the following view: def load(request): form = LoadForm() context = { 'form': form, 'title': 'Nuovo Carico', } return render(request, 'warehouse/load.html', context) and the following template: {% extends "masterpage.html" %} {% load static %} {% block headTitle %} <title>{{title}}</title> {% endblock %} {% block contentHead %} {% endblock %} {% block contentBody %} {% load document_tags %} {% load custom_tags %} {% load crispy_forms_tags %} <FORM method="POST" autocomplete="off"> {{ form.media }} {% csrf_token %} <div class="alert alert-info"> {{ title }} </div> {% crispy form %} <input type="submit" class="btn btn-primary margin-left" value="CARICA"> </FORM> {% endblock %} For some strange reason the form will not show up, I just see the title and the input button. I've tried the very simple form.as_p with no crispy, but still nothing... By looking at the sourse code on the browser I see there is a div with class 'form-row' but not form in it... looks strange. Any help? thank you very much. Carlo -
Call Postgres functions From Django
I am working on a Django Project with a Postgres SQL Database. I have written a function that runs perfectly on Postgres 10. CREATE FUNCTION sample_insert(_sno integer, _siid integer, _sd date, _ed date, _sid integer, _status boolean) RETURNS void AS $BODY$ BEGIN INSERT INTO sample (sno, siid, sd, ed, sid, status) VALUES (_sno, _siid, _sd, _ed, _sid, _status); END; $BODY$ LANGUAGE 'plpgsql' COST 100; -
Creating room link with models
I've been developing a sports team application with Django and Channels where the room name (included in the link) corresponds to the 'team code' (Primary key). The users are connected to the teams via a foreign key and I'm trying to find a way to redirect users to their team's chat room once they log in/register. Models.py: class Team(models.Model): Name = models.CharField(max_length=60) code = models.CharField(max_length=6, blank=True, primary_key=True) def __str__(self): return self.Name def save(self, *args, **kwargs): # Saves the generated Team Code to the database if self.code == "": code = generate_code() self.code = code super().save(*args, **kwargs) class User(AbstractBaseUser, PermissionsMixin): USER_CHOICES = [ ('CO', 'Coach'), ('PL', 'Parent'), ('PA', 'Player'), ] User_ID = models.UUIDField(default=uuid.uuid4, primary_key=True) email = models.EmailField(verbose_name='email', max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) is_active = models.BooleanField(default=True) ## Everything within these comment tags is_admin = models.BooleanField(default=False) ## define the permissions is_staff = models.BooleanField(default=False) ## that the user will have unless is_superuser = models.BooleanField(default=False) ## changed by the superuser/admin. is_coach = models.BooleanField(default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) # Ensures that the user isn't deleted when a team is deleted user_type = models.CharField(choices=USER_CHOICES, default='CO', max_length=20) # Useful for when the app wants to identify who has certain … -
Django 3.2 exception: django.core.exceptions.ImproperlyConfigured
I'm upgrading to django 3.2 but as per it's release notes, it says: The SECRET_KEY setting is now checked for a valid value upon first access, rather than when settings are first loaded. This enables running management commands that do not rely on the SECRET_KEY without needing to provide a value. As a consequence of this, calling configure() without providing a valid SECRET_KEY, and then going on to access settings.SECRET_KEY will now raise an ImproperlyConfigured exception. I'm pretty certain that error is because of such. Can someone help me to solve this? How can i check if my secret key is valid or not and also generate new if needed? -
python-django load model OSError
model = load_model('./saved_model.h5') "OSError: SavedModel file does not exist at: ./saved_model.h5{saved_model.pbtxt|saved_model.pb}" The model is well called in python, not in django, but not in django. The model is in the same folder as the code. What is the problem? (For your information, I already installed h5py..!) -
Can I replace django admin panel login code by Amazon Cognito?
I want to replace admin or superuser login by cognito credentials. Is it possible to do that? -
Input Search in django admin filter
Is it possible to create input search in django admin filter without custom template? Something like this, but without custom template? Example of search field -
django uwsgi logto function not work in docker
dockerizing a django app with uwsgi uwsgi [uwsgi] chdir = /app http = :12345 socket=127.0.0.1:8002 wsgi-file=leak/wsgi.py static-map = /static=static processes=4 threads=2 master=True log-master = true threaded-logger = true logto=/var/log/leak.log log-maxsize = 100000 threaded-logger = true pidfile=uwsgi.pid env = DJANGO_SETTINGS_MODULE=leak.settings.development dockerfile FROM python:3.6.8-alpine COPY requirements /app/requirements WORKDIR /app RUN apk update && apk add make \ && apk add --virtual mysqlclient-build gcc python3-dev musl-dev \ && apk add --no-cache mariadb-dev \ && apk add --virtual system-build linux-headers libffi-dev \ && apk add --no-cache jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ && apk add --no-cache bash bash-doc bash-completion libxml2-dev libxslt-dev \ && pip install --upgrade pip setuptools wheel \ && pip install -r requirements\ COPY . /app CMD ["sh","run.sh"] run.sh #!/usr/bin/env sh uwsgi --ini uwsgi.ini after docker build && docker run the logpath "/var/log/leak.log" not create and without any errors. but its worked without docker. how can i fix it -
Django Admin Add Object - Customize Dropdown
Moin Moin! I have this model in my models.py: class BranchChief(models.Model): BranchChiefID = models.ForeignKey(User, on_delete=models.CASCADE) BranchID = models.ForeignKey('Branch', db_column='BranchID', on_delete=models.CASCADE) When adding a new object I get a dropdown-field for the field BranchChiefID showing all available usernames. How can I change it to show first_name and last_name to identifiy the user in the dropdown-field? (username is (and must be) a random-number) Thank you for your help! -
Django query fails with _id that is not used or created or referenced to
I have used the queryset before though this is my first attempt to JOIN tables but it's not working so far. I am using django 3.2 and python 3.8.1 my models.py class Mainjoinbook(models.Model): fullsitename = models.TextField(primary_key=True) creationdate = models.DateTimeField() entrytypeid = models.BigIntegerField(blank=True, null=True) title = models.TextField(blank=True, null=True) tickettype = models.TextField(blank=True, null=True) ticket = models.TextField(blank=True, null=True) status = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'mainlogbook' class Sitelocation(models.Model): site_name = models.TextField(primary_key=True) latitude = models.TextField(blank=True, null=True) longitude = models.TextField(blank=True, null=True) sites = models.ForeignKey(Mainjoinbook, on_delete=models.DO_NOTHING) class Meta: managed = False db_table = 'tblsiteaccess' I am trying to get all values from both tables joined in my views.py qrylocations = Sitelocation.objects.select_related('sites').filter(sites__status='OPEN') this results in this error as that column is created by django but doesn't belong to the table. I still can't workout how to resolve this as I have tried many options but always get in some kind of error and I hope someone can help me to see what I'm doing wrong in joining the tables on the primary keys defined psycopg2.errors.UndefinedColumn: column tblsiteaccess.sites_id does not exist the SQL output shown is as below. output from qrylocations.query SELECT "tblsiteaccess"."site_name", "tblsiteaccess"."latitude", "tblsiteaccess"."longitude", "tblsiteaccess"."sites_id", "mainlogbook"."fullsitename", "mainlogbook"."log_id", "mainlogbook"."creationdate", "mainlogbook"."entrytypeid", "mainlogbook"."title", "mainlogbook"."tickettype", "mainlogbook"."ticket", "mainlogbook"."status" … -
a bytes-like object is required, not 'FieldFile'
I am building a BlogApp and I am trying to download the .zip of the blogs. What i am trying to do :- I am trying to download all the texts with images in .zip file BUT when i remove image from the download files then it works fine BUT when i add image in download items then it is keep showing me :- a bytes-like object is required, not 'FieldFile' models.py class Blog(models.Model): name = models.CharField(max_length=25,default='username.txt') image = models.FileField(default='') views.py def download(request): response = HttpResponse(content_type='application/zip') zf = zipfile.ZipFile(response, 'w') zf.writestr(README_NAME, README_CONTENT) scripts = Blog.objects.all() for snippet in scripts: zf.writestr(snippet.name, snippet.image) response['Content-Disposition'] = f'attachment; filename={ZIPFILE_NAME}' return response When i remove snippet.image then it download prefectly but after adding it it is showing that error. I have no idea what to do. Any help would be Appreciated. Thank You in Advance. -
how to create django-views links within javascript
I have django-application with a template-html which contains a javascript which uses AJAX to get results (while typing) of a search engine and populate a list. Now, I want this list to be links with django-patterns based on these results. How would I do that. As far as I understand, I cannot use django template-syntax within javascript. Can anybody help me with some hints? (Sorry, if any information is missing - I'm new to django/javascript/ajax) -
I cannot Display MySql data in html after fetching from database fetched data can be seen in Server ( CMD )
i have tying to display data from database only by writing query in python django but i am facing some issue what cause this issue model.py class add_topic(models.Model): test_id=models.IntegerField() topic_name=models.CharField(max_length=100) class Meta: db_table = "opicc"; view.py def addassessment(request): c = connection.cursor() c.execute('SELECT test_id, topic_name FROM test_topic') results=c.fetchall() context={"topics":results} return render(request,'add_assessment.html',context) display.html <div class="form-group"> <label>Post To</label> <select name="event_made_for" required="" class="custom-select"> <option>Select Whome you want to set this Event</option></select> {% for i in topics %} <option value="{{i.test_id}}">{{i.topic_name}}</option> {%endfor%} </select> <!--If i print that context--!> {topics} </div> output: ((8, 'hello'), (9, 'Antony')) i am getting this values if i run the code but i cant display individual values