Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selenium,Django, On Ubuntu 20.04 digital ocean VPD
I have created the web scraper and integrated it with Django. Everything is working perfectly fine. Now I want to host that Django app with webscraper on the VPS so that he can access it anywhere. I am using gunicorn and nginx too. I tried that Django app with webdriver.remote() using seleniumgrid its working fine on my normal windows environment, but as soon as I put it on my ubuntu vps it works only in half of cases - like all my Django stuff is accessible and operational, but when my django calls the scraper, it just passes without any response. def chromedriver_setup(): user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36' # proxies = proxies = [{"_id":"62cd1bf852694154bb14f2e7","ip":"178.32.148.251","anonymityLevel":"elite","asn":"AS16276","city":"Gravelines","country":"FR","created_at":"2022-07-12T07:00:08.515Z","google":True,"isp":"OVH SAS","lastChecked":1657848951,"latency":5.13,"org":"MICHOTTE Maxime","port":"8080","protocols":["socks4"], "speed":37,"updated_at":"2022-07-15T01:35:51.569Z" },{"_id":"60d613cdce5b3bb0e932edce","ip":"64.227.62.123","port":"80","anonymityLevel":"elite","asn":"AS14061","city":"Santa Clara","country":"US","created_at":"2021-06-25T17:35:09.953Z","google":True, "isp":"DigitalOcean, LLC","lastChecked":1657847332,"latency":153,"org":"DigitalOcean, LLC","protocols":["http"], "speed":306,"updated_at":"2022-07-15T01:08:52.862Z" ,"upTime":99.98473981382573,"upTimeSuccessCount":6552,"upTimeTryCount":6553}] # random_ip = random.choice(proxies) # PROXY = str(random_ip["ip"] + ":" + random_ip["port"]) option = webdriver.ChromeOptions() option.add_argument("--headless") option.add_argument(f'user-agent={user_agent}') option.add_argument("--window-size=1920,1080") option.add_argument("--start-maximized") option.add_argument("--disable-gpu") # # option.add_argument('--proxy-server=%s' % PROXY) option.add_experimental_option("excludeSwitches", ["enable-automation"]) option.add_experimental_option('useAutomationExtension', False) option.add_argument("--disable-blink-features=AutomationControlled") option.add_experimental_option("detach", True) print("chrome driver setup passed") driver = webdriver.Remote( command_executor='192.168.72.1:4444', desired_capabilities = DesiredCapabilities.CHROME, options=option, ) return driver Is there any way I can solve that issue or test i..? -
AttributeError: type object ' ' has no attribute 'object'
I am working on REST API and i get an error saying "AttributeError: type object 'Project' has no attribute 'object'" when trying to access http://127.0.0.1:8000/projects/ here is my files : --> views.py: from django.http import JsonResponse from .models import Project from .serializers import ProjectSerializer def project_list(request): drinks = Project.object.all() serializer = DrinkSerializer(projects, many=True) return JsonResponse(serializer.data) --> models.py from django.db import models class Project(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) def __str__(self): return self.name + ' ' + self.description --> urls.py from django.contrib import admin from django.urls import path from projects import views urlpatterns = [ path('admin/', admin.site.urls), path('drinks/', views.drink_list), ] -
Django tests suddenly failing for no apparent reason
I have a django project with hundreds of unit tests and after a big update that added about 50 more tests, all the project's tests that creates an instance of a specific model are failing with the following error message: Traceback (most recent call last): File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in _execute self.db.validate_no_broken_transaction() File ".../venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 437, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. During handling of the above exception, another exception occurred: File ".../venv/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 653, in first for obj in (self if self.ordered else self.order_by('pk'))[:1]: File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1145, in execute_sql cursor.close() File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 83, in close while self.nextset(): File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 137, in nextset nr = db.next_result() MySQLdb._exceptions.OperationalError: (2006, '') The update did not change … -
Got Errno 13 when trying to save image with Pillow [Python, Django]
Got [Errno 13] when trying to save images using Pillow. Exact error is: PermissionError: [Errno 13] Permission denied: 'C:/Users/django/PycharmProjects/django/csvs/photos/blah-summer-jean\cropped-788x1000'. My code is below: from PIL import Image from blah import settings from django.core.files.storage import default_storage from blah.storage_backends import MediaStorage import os app_storage = None image_dir = 'C:/Users/django/PycharmProjects/sassigen/csvs/photos/blah-summer-jean' cropped_dir = 'C:/Users/django/PycharmProjects/sassigen/csvs/photos/blah-summer-jean/cropped-788x1000' if settings.DEBUG: app_storage = default_storage else: app_storage = MediaStorage def crop_image(image): try: img = Image.open(image) width, height = img.size if width <= 788 and height <= 1000: pass else: xcenter = img.width / 2 ycenter = img.height / 2 x1 = xcenter - 488 y1 = ycenter - 600 x2 = xcenter + 488 y2 = ycenter + 600 image_to_crop = img.crop((int(x1), int(y1), int(x2), int(y2))) output_size = (788, 1000) final_image = image_to_crop.resize(output_size) img.close() return final_image except AttributeError: pass except Exception as e: raise e for each_image in os.listdir(image_dir): cropping = crop_image(os.path.join(image_dir, each_image)) if not os.path.exists(cropped_dir): os.mkdir(cropped_dir) cropping.save(os.path.join(cropped_dir, each_image), 'jpeg') -
Uploading Cyrillic files in Django
Good afternoon. I am writing share for a corporate portal. I ran into such a problem that after downloading files with Cyrillic, I try to download them, and Django gives a path error urls 404 the path to the file was not found. Tell me where I'm wrong. My models.py: from django.db import models from datetime import datetime from django.contrib.auth.models import User def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.owner.id, instance.name) class DirectoryItem(models.Model): name = models.CharField(max_length=200, default="New Folder", blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE) # a parent folder of null/blank would indicate a root folder. # A users root folder is created upon registration date_created = models.DateTimeField(default=datetime.now) is_recycled = models.BooleanField(default=False) # auto_now: updates on changes. date_recycled will be last change # (Improve - create custom save function) date_recycled = models.DateTimeField(auto_now=True) is_public = models.BooleanField(default=False) is_shared = models.BooleanField(default=False) class Meta: abstract = True class Folder(DirectoryItem): parent_folder = models.ForeignKey( "self", on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class File(DirectoryItem): parent_folder = models.ForeignKey(Folder, on_delete=models.CASCADE) file_source = models.FileField(upload_to=user_directory_path) file_type = models.CharField(max_length=20) def __str__(self): return self.name My views.py , the function responsible for downloading the file: def folders(request, folder_id): requested_folder_id = folder_id cur_user_id = request.user.id requested_folder = Folder.objects.get(id=requested_folder_id) # Is it the users folder? if (requested_folder.owner.id != cur_user_id): # Does … -
Python Django always passes id 1 on ForeignKey with to_field
I'm new to Django and trying to create a small application that shows scanned data from virtual machines that are inserted in a table named HostsFixDataScans. To access the scanned data in HostsFixDataScans via the Hosts model, I defined a ForeignKey with to_field. But unfortunately, the data returned by the linked HostsFixDataScans are wrong. I checked the SQL statements and when requesting the HostsFixDataScans table, not the id of the Host is used, but always 1. My domain = models.ForeignKey(Domains, on_delete=models.CASCADE) definition which does not use to_field works correctly. I'm pretty sure, I have a misunderstanding of the definition of this relationship. Maybe you could give me some hints how to solve the problem? Many thanks in advance! Here are the shortened definitions of the models: class Os(models.Model): operatingsystem = models.CharField(max_length=32) lsbdistcodename = models.CharField(max_length=32) lsbdistrelease = models.CharField(max_length=32, db_collation='ascii_bin') lsbmajdistrelease = models.IntegerField() remarks = models.CharField(max_length=256, blank=True, null=True) class HostsFixDataScans(models.Model): host_id = models.PositiveIntegerField(primary_key=True, unique=True) scan_id = models.PositiveIntegerField() os = models.ForeignKey(Os, on_delete=models.CASCADE) class Hosts(models.Model): hostname = models.CharField(max_length=256) domain = models.ForeignKey(Domains, on_delete=models.CASCADE) is_virtual = models.PositiveIntegerField(blank=True, null=True) os = models.ForeignKey(HostsFixDataScans, to_field='host_id', on_delete=models.CASCADE) -
How do I port Django's ModelMultipleChoiceField widget to reactjs?
This is the widget I'm talking about: https://docs.djangoproject.com/en/4.0/ref/forms/fields/#modelmultiplechoicefield Here's a picture of it: https://i.stack.imgur.com/2tZhv.png Rendering it statically and preserving the style was easy, but I'm not sure how to do that dynamically, so that I'm able to dynamically feed it a list of input and be able to submit or change it or use the provided search bar. -
protect SQL injection on django Rest API
For penetration testing purpose, I am tring sql-injection to my Django Rest API,And I can successfully take schema , table and rows information by SQLmap. I was try several times,It was just simple API. I was create function based view, also a class base view, I was try with cursor and also try ORM.raw query try with parameterize. but every time I can injected sql by SQLMAP. I can't believe, how it happens, but I see result in my implementation. I am sure that I follow proper way. Please suggest my , how can I protect all type of API, which url have params. -
Django Rest Framework Viewset Filter By Value
Let's say I have a DRF viewset like so class SecretViewset( viewsets.ModelViewSet, ): queryset = Secret.objects.all() serializer_class = SecretSerializer @action(methods=['GET'], detail=True) def name(self, request, pk=None): secrets = Secret.objects.filter(name__contains=pk) return Response(self.get_serializer(secrets, many=True).data) I want to be able to search via a name in the URL. So /api/secrets/name/NAMEHERE/ However, because ModelViewset implements mixins.Retrieve, it returns a 404 because it searches /api/secrets/ID/ first and doesn't find it, therefore throws a 404. What would the proper way be to go about adding the ability to search by name as described above? Edit Adding my urls conf from .Secret.viewsets import SecretViewset router = routers.SimpleRouter() router.register(r'^api/secrets', SecretViewset, 'secrets') # Later on, router gets imported and added on via `urlpatterns += router.urls` -
Django celery with redis is executing same task multiple times
I'm trying to creating a background task with Django celery and Redis as broker. this task is being sent from models when model post save. But the problem is that, the same task is getting executed 1000 of times (other debug or add task are working fine). i have already tried this method but this didn't resolve the issue. Please find the below codes for your reference and help to resolve. Thanks in advance. models.py from django.db.models.signals import post_save from django.dispatch import receiver from student.tasks import create_student_subject_tryout_result, add @receiver(post_save, sender=TryoutSubmission, dispatch_uid='create_student_subject_tryout_result') def result_calculation(sender, instance, **kwargs): if instance.status == 'C': print('Calculating result') create_student_subject_tryout_result.delay(instance.student.id, instance.tryout.id) celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eec.settings') app = Celery('eec') app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.broker_transport_options = {'visibility_timeout': 3600} . app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') tasks.py from celery import shared_task import tryout.models @shared_task(bind=True) def create_student_subject_tryout_result(self, student_id, tryout_id): tryout_submission=tryout.models.TryoutSubmission.objects.get( student_id=student_id, tryout_id=tryout_id ) tryout_questions = tryout_submission.tryout.tryoutquestion_set.all().count() answered_qs = tryout_submission.tryout.tryoutanswersubmission_set.filter( is_answered=True).count() correct_ans = tryout_submission.tryout.tryoutanswersubmission_set.filter( is_correct=True).count() tryout_submission.total_questions = tryout_questions tryout_submission.answered_questions = answered_qs tryout_submission.correct_answers = correct_ans tryout_submission.total_time = tryout_submission.end_time - tryout_submission.start_time tryout_submission.save() return "Result created" settings.py CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' -
Why am I getting a IntegrityError at, null value in a column that doesn't exists... Django
I am trying to hit an external api, when a user submits a form. I am using Django and Postgresql My Model class League_Mod(models.Model): host = models.CharField(max_length=50) Espn_League_Id = models.IntegerField(unique = True) Espn_S2 = models.CharField(max_length=3000) Espn_Swid = models.CharField(max_length=300) bigdata = models.JSONField(default=dict,null=True) My Serializer class Meta: model = League_Mod fields = ['host', 'Espn_League_Id','Espn_S2','Espn_Swid','bigdata'] Views where Owners is a large dictionary. league_data = { 'host' : request.data['host'], 'Espn_League_Id' :request.data['Espn_League_Id'], 'Espn_S2' : request.data['Espn_S2'], 'Espn_Swid' : request.data['Espn_Swid'], 'bigdata' : Owners } serializer = LeagueSerializer(data=league_data) print(serializer) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) my print serializer runs, and prints the data correctly. But I get an error: integrityError at /wel/ null value in column "hello" of relation "api_league_mod" violates not-null constraint DETAIL: Failing row contains (11, JPFL, 216415, AEAylLD7uSQQ7%2BenPr6av1H%2Fx0Hqbbpn8Jvr91ngxM1ll5ynO685mhN%2BSu..., {D19D67CA-C981-4CA2-8463-AF4111D2E8E2}, {"Person1": {"2010": [0, 1, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5, 6,..., null). I am very unclear where the column hello is... and there is no relation to api_league_mod Model, so don't quite understand why my serializer is returning unvalid Any insight would be appreciated. Thanks! -
showing a field of multiplke choises in django admin
In my django admin I'm trying to show a field of my model which may has multiple values (like a list). Here's my definition of the field in models.py related_countries = CountryField( multiple=True, blank=True ) So when I create a model in the database, what I got as the value of the field is something like AL,AS Then for my admin page, I didn't put it in the list_display because I don't want it to be shown at the page where all the records of this models is printed. I want it to be shown only when I click one of the record and check the detail of this record. So when I'm at the page that shows everythhing, it works well. Also, the record cannont be modified on the admin page so I have this function on my admin code: def has_change_permission(self, request: HttpRequest, obj=None) -> bool: return False And there comes the issue: When I enter the page for the detail of the record, I got a TypeError at XXX unhashable type: 'list' and I'm pretty sure it comes from the field related_countries. Cause when I removed the function to make it possible to modify the record, anything … -
Render Excel templates
I'd like to have the ability to render Excel template files: and not create Excel files programmatically. There is a lib Templated-docs. But the templates themselves must be in on of the OpenDocument formats: .odt, .ods, .odp or .odg. Those templates are rendered to excel futher. This fact affects on formatting features when rendering to Excel. Is there any possibility to render directly to Excel file template? -
how to set a default for multiselect field in django
I have an Account model that extends django's custom User model: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group, related_name='joined_group', blank=True) created_groups = models.ManyToManyField(Group, blank=True) EMAIL_PREFERENCES = [ ('user_emails', 'User Emails'), ('group_emails', 'Group Emails'), ('leader_emails', 'Leader Emails'), ] email_preferences = MultiSelectField( verbose_name = 'Email Preferences', choices=EMAIL_PREFERENCES, blank=True, max_choices=3, max_length=255, ) When a User registers or signs up, as of now, they create a connected Account with the same id and pk with the fields of joined_groups and created_groups empty. However, they also have none of the email_preferences selected either. Here in lies my issue. I want a User who signs up to have the default for email_preferences true for all of them. Then, if they prefer to not receive any emails, they can edit their email_preferences on their Account page. Lastly, once the email_preferences have been selected, I need to add the conditional into the view to see whether or not this User should receive email notifications: For when a User creates a Group: class CreateGroup(CreateView): model = Group form_class = GroupForm template_name = 'create_group.html' def form_valid(self, form): group = form.save() group.joined.add(self.request.user) account = self.request.user.account account.created_chaburahs.add(group) account.joined_chaburahs.add(group) email = account.user.email # celery task to send email create_group_notification_task.delay(email) return HttpResponseRedirect(reverse('group_detail', … -
Adding condition to DeleteView in Django
I am learning basics of Django and trying to add a condition before deletion of Ingredient instance in a generic DeleteView. But it looks like DeleteView is just ignoring my condition. What am I doing wrong? Thank you in advance for looking at my question! class IngredientDelete(LoginRequiredMixin, DeleteView): model = Ingredient template_name = "inventory/ingredient_delete_form.html" success_url = "/ingredient/list" def delete(self, request, *args, **kwargs): object = self.get_object() if len(object.reciperequirement_set.all()) > 0: object.delete(save=False) messages.error("You can't delete an ingredient if it is used in Menu Items. Please update Menu items first. You can check related Menu items list on the Ingredient Details page") return render(request, "ingredient/<pk>", messages) else: return super().delete(request, *args, **kwargs) in python shell, for the instance object I try len(object.reciperequirement_set.all()) and get 1, so I suppose the query in my condition is set correctly. At local host page for the same Ingredient instance I get the error page: ProtectedError at /ingredient/23/delete ("Cannot delete some instances of model 'Ingredient' because they are referenced through protected foreign keys: 'RecipeRequirement.ingredient'.", {<RecipeRequirement: menu item: testdel, price: 34.00, ingredient: testingr: 22.00 tsp>}) Request Method: POST Request URL: http://127.0.0.1:8000/ingredient/23/delete Django Version: 4.0.4 Exception Type: ProtectedError -
implementing multi user types for hospital management system
so I am building a hospital management system as my pet project in Django, and one thing that I realized is that you need implement a 3 user multi system which includes the HR, staff(doctor) and patient. Been surfing through the internet for the best implementation and came up short. The best I saw was this tutorial blog on How to implement multi user system, but it doesn't cover on using more than 3 user like I want to. This is my current user/models.py from django.db import models from django.contrib.auth.models import AbstractUser USER_CHOICE = [ ('D', 'Doctor'), ('P', 'Patient'), ('R', 'Receptionist'), ('HR', 'HR') ] # Create your models here. class User(AbstractUser): """ user class for different users in the database """ user_type = models.CharField(choices=USER_CHOICE, max_length=3, default=None) def is_doctor(self): """ return True if the user is a doctor and False if not """ if self.user_type == 'D': return True return False def is_patient(self): """ return True if the user is a patient and False if not """ if self.user_type == 'P': return True return False def is_receptionist(self): """ return True if the user is a receptionist and False if not """ if self.user_type == 'R': return True return False def is_hr(self): … -
Make Django form choices depend on values submitted in a previous form
I'm using django-formtools to create a multi-step form wizard. I want to use data entered in the first step to call an API, then use the response data in the next step as a ChoiceField. This is what my code currently looks like: views.py from server.companies.models import Company from server.data_sources.models import DataDictionary, DataSource from django.shortcuts import render from formtools.wizard.views import SessionWizardView import json import logging from server.data_sources import ds from server.data_sources.models import SOURCE logger = logging.getLogger("server." + __name__) def create_records(data): if not data or data == {}: return name = data.get("company_name") is_sandbox = data.get("is_sandbox") city = data.get("city") state = data.get("state") username = data.get("username") password = data.get("password") data_source = DataSource.objects.create( name=name, source_type=SOURCE, ) ds.login(data_source, username, password) company = Company.objects.create( name=name, data_source=data_source, ) return company class Wizard(SessionWizardView): template_name = "wizard.html" def done(self, form_list, **kwargs): return render( self.request, "done.html", {"form_data": [form.cleaned_data for form in form_list]}, ) def get_form_step_data(self, form): return form.data def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) company = None # determine the step if not given if step is None: step = self.steps.current if step == "0": if form.is_valid(): step_zero_data = form.cleaned_data company = create_records(step_zero_data) source = company.data_source data_dict = {} for field in ds.select( company, "DATADICT", ["dd_dbf", … -
Heroku Django post-gis extension: Error "no attribute 'geo_db_type'" problem when migrating a new model that contains geo elements
I'm running into this issue when deploying my django app on heroku. It had be building and deploying fine before I edited my django model to include a geometry field: geom = models.PointField(verbose_name='geo',srid = 4326) Now it builds successfully, but then fails at this migration code in the Procfile `release: python manage.py migrate` The migration file is successfully in my git repo. And locally I was able to run python manage.py migrate successfully. When I go to migrate on heroku I get the below error. AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' It seems to indicate that there is something "geo-related" missing, but I can't figure out what since I have created a postgis extension on the postgres db in heroku and I have the heroku-geo-buildpack along with the heroku/python buildpack. On heroku I have python 3.10 and locally it's Python 3.9.13. In my settings.py file I have: 'ENGINE':'django.contrib.gis.db.backends.postgis', in the DATABASES and 'django.contrib.gis', in INSTALLED_APPS Here's the post-gis extension on the heroku postgres database: And the two buildpacks set in heroku: Thank you for any help or guidance! -
"Invalid value." error while using django rest framework Serializer
I am trying save some information from a csv file into the DB using django rest framework, currently I am not sure where is the issue if it is in the view or something in the model, to test it out I am sending the data as it is arriving to the serializer Here there is my view.py import re import csv import codecs import pandas as pd from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.shortcuts import render from rest_framework.decorators import api_view # Create your views here. from rest_framework import viewsets,status from .serializer import tripSerializer #,DataSourceSerializer from .models import Trips from rest_framework.response import Response class TripViewSet(viewsets.ViewSet): def list(self, request): queryset = Trips.objects.all() serializer = tripSerializer(queryset, many=True) return Response(serializer.data) def insert(self, request): file=codecs.EncodedFile(request.FILES.get("file").open(),"utf-8") print(type(file)) reader = pd.read_csv(file, delimiter=";") reader.columns = ['region','origin_coord','destination_coord','datetime','datasource']; reader=reader.to_dict(orient = 'records')[0] print("--------------------------------------------------------") print("DATA inicial",reader) print("--------------------------------------------------------") data={'region': 'Prague', 'origin_coord': 'POINT (14.4973794438195 50.00136875782316)', 'destination_coord': 'POINT (14.43109483523328 50.04052930943246)', 'datetime': '28/05/2018 9:03', 'datasource': 'funny_car'} serializer = tripSerializer(data=reader) print("trying to validate") if serializer.is_valid(): serializer.save() return Response({"status":"success"}, status=status.HTTP_200_OK) else: return Response({"status":"Error!!","data":serializer.data,"Error:":serializer.errors,"message_error":serializer.error_messages}, status=status.HTTP_400_BAD_REQUEST) Serializer.py from django.shortcuts import render # Create your views here. from dataclasses import field, fields from rest_framework import serializers from .models import Datasources, Regions, Trips … -
how to serialize two classes have one to many relation in django
this is my models class Users(models.Model) : name = models.CharField(max_length=20 , blank=False , null=False) email = models.EmailField(max_length=50 , blank=True , null=True) password = models.CharField(max_length=30 , blank=False , null=False) birthday = models.DateField(null=False) photo = models.ImageField(upload_to = 'user_photos/%y/%m/%d') #friend = models.ManyToManyField('self',through='Notif',null=True,related_name='friend') class Product(models.Model): pub_date = models.DateTimeField(default=datetime.now) price = models.DecimalField(max_digits=100000,decimal_places=5,null=False,blank=False) size = models.IntegerField(null=True,blank=True,default='undefined') photo = models.ImageField(upload_to = 'product_photos/%y/%m/%d',null=True) #for 1--n relation with users user_id = models.ForeignKey(Users,on_delete=models.CASCADE,null=True,related_name='user') this is my serializers.py class ProductSerializer (serializers.ModelSerializer): class Meta : model = Product fields = '__all__' class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' i want to send product object with the email of his user what i have to do in serializers and views to make it note i use function based views in my views -
How can I store images on server and serve them with nginx and django?
I've created a Django app and I'm using Gunicorn and Nginx with it on an Ubuntu server. Nginx serve my static files and it work great for css files and javascript, but I have problem with images. App is my personal blog site and I'm using Django ckeditor for uploading images and writing some text.Everything worked as it should while I was using local server, but when i deploy it on cloud server images are not displayed. here's my project/app/models.py from django.db import models import uuid from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Category(models.Model): title = models.CharField(max_length=150) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=150) description = models.CharField(max_length=150, blank=True, null=True) body = RichTextUploadingField(blank=True, null=True) profile_image = models.ImageField(null=True, blank=True, default='default.png') category = models.ForeignKey(Category, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Meta: ordering = ['-created'] The code below is in settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_ROOT = '/var/www/my-website.com/media' STATIC_ROOT = '/var/www/my-website.com/static' CKEDITOR_UPLOAD_PATH = 'uploads/' In project urls.py I add: urlpatterns = [ . . . path('ckeditor', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to configure data migration from one model to another . Django?
There is model Leads with fields : name, phone, email, address and I create model Contacts with the same fields but with processed data from Leads for example, combine all leads with the same names and phone numbers into one contact, etc. how to implement it? whether to create a migration or a . how it is better to implement it? -
accordion with for loop to only open one item at a time
I am trying to add an interactive id to my accordion, but something is off in my code and the accordion opens every accordion item, all I want is to be able to open one accordion item at a time when clicking on it. {% for study in studies %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="heading{study.uid}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs- target="#collapse{study.uid}" aria-expanded="true" aria- controls="collapse{study.uid}"> {{ study.uid }} </button> </h2> <div id="collapse{study.uid}" class="accordion-collapse collapse" aria- labelledby="heading{study.uid}" data-bs-parent="#accordionExample"> <div class="accordion-body"> text </div> </div> </div> {% endfor %} -
Python/Django - Best way to avoid UnboundLocalError when a list is empty
I'm using a list to get data from an API. This list is created with a code like this: mylist = [] for batch in stream: for row in batch.results: data = {} data["color"] = row.color data["count"] = row.count mylist.append(data) And the list end up being something like: mylist = [{'color':'red','count':5}, {'color':'blue','count':7}] And then I send it to the Django template using something like this: context = { 'mylist' : mylist, 'data' : data, } return render(request, 'page.html', context) This works OK most of the time. But sometimes there is no data to send, so the API doesn't send anything and mylist is empty. When that happens, I get an error: UnboundLocalError at /page local variable 'data' referenced before assignment I've "solved" it with the following code: if not mylist: data = {"error": "no data"} That removes the error, but seems very "hacky". I don't need that info in my list. If there is no data, I would probably prefer to have the list empty (so I can do an "if" to check if it's empty or not and stuff like that). Is there a better solution? Thanks! (I'm learning Python and Django, so maybe most of my code can … -
GCBV Generic Class Based View, Django Classes Issue
$ Hello, I was trying to use "GCBV Generic Class Based View" for edit a post, but it seems not working and event it django can't find my HTML and I don't know why , Hope I get some support …. $ edit button link {% if post.created_by == user %} <div class="mt-3"> <a class="btn btn-success float-end" href="{% url 'edit_post' post.topic.board.pk post.topic.pk post.pk %}">Edit</a> </div> {% endif %} $ edit HTML Page {% extends 'base.html' %} {% load static %} {% block title %}Edit Post{% endblock %}<!-- | Page-title--> {% block content %} <link rel="stylesheet" href="{% static 'css/boards.css' %}"> <div class="newtopic"> <div class="container container-newtopic w-50"> <h1>Edit Post</h1> <br> {% include 'parts/alerts.html' %} <div aria-label="breadcrumb"> <ol class="breadcrumb n1-head"> <li class="breadcrumb-item"><a href="{% url 'boards' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'topics' post.topic.board.pk %}"> {{post.topic.board.name}}</a></li> <li class="breadcrumb-item active" aria-current="page"><a href="">Edit Post</a></li> </ol> </div> <form method="POST" action="" novalidate class="mb-4"> {% csrf_token %} {% include 'includes/form.html' %} <button type="submit" class="btn main-btn w-100 rounded-pill mt-5"> Save Changes </button> </form> </div> </div> {% endblock %} $ Views.py @method_decorator(login_required, name='dispatch') class PostUpdateView(UpdateView): model = Post fields = ('message',) template_name = 'edit_post.html' pk_url_kwarg = 'post_id' context_object_name = 'post' def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_date = timezone.now() …