Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove Z from DateTimeField in serializer
Is there a way to make my serializer print the datetimefield by default like this 2022-03-28T00:00:00+00:00 Instead of this 2022-03-23T03:16:00Z I get the first output when I do this return obj.time.isoformat() -
PythonAnywhere "ModuleNotFound Error django"
Im working on hosting a Django app on pythonanywhere. I had it semi working before changing a few things that a guide suggested, before it started running a ModuleNotFoundError saying Django was not installed, even though I did install it in the virtual environment. The changes I made before this started happening are: I remade my Github repo by incorporating a .gitignore file before pushing to the repo as suggested by the guide (I forgot to make this file the first time I made the repo and cloned into PythonAnywhere). The file consists of this: # Python *.pyc *~ __pycache__ # Env .env myvenv/ venv/ # Static folder at project root /static/ # macOS ._* .DS_Store .fseventsd .Spotlight-V100 # pycharm .idea/ I pushed my project to Github, and then at the repo on github I manually inserted this into the .gitignore file before cloning to PythonAnywhere: wintergardendjango/settings.py I then cloned this repo via the console on pythonanywhere and made a new virtual environment where I again installed django. I updated all my paths to reflect the new virtual environment ect. The error being called is in the WSGI file which is: # To use your own django app use code … -
Django - is there way to connect Cytoscape? (Not CytoscapeJs)
I am looking a way to use Cytoscape library with Python via Django. I would like to go to route and be able to click node and have an output. I want this to be similar to this one video: https://www.youtube.com/watch?v=g8xBlilTV4w I have represented this problem on image below: enter image description here How should I tackle the problem? -
Connecting to same database, different schema/table names in Django schema
I'm trying to figure out the best way to create a Django schema that can dynamically switch between schema with similar structure in the same database (i.e. similar table names, with an appended suffix) so that I can build a graphene application and change the suffix based on my query. For example, if I have a book table: class Book(models.Model): class Meta: db_table = "book_{suffix}" ... I'd want to switch the database connection's schema and set the suffix before any queries are executed. I've not seen an example of how to best handle that. -
Changing foreign key based on varying input
I've built a review tool for various systems so that managers can review their employees current access to those systems. It runs on a campaign by campaign basis where the team who manages this access selects a specific system when kicking off the campaign. I have a review model that relates to the campaign, the manager doing the review, the employee being reviewed, as well as the employee's account being reviewed. However, I currently have to hard code the foreign keys like so acsAcct = models.ForeignKey('acsUser', null=True, blank=True, on_delete=models.CASCADE) iseAcct = models.ForeignKey('iseUser', null=True, blank=True, on_delete_models.CASCADE) ... This creates an issue when I try to dynamically create review instances with my createReview class method. Currently I have to append the account to the review later by checking the campaign's system and then going to the appropriate model and finding the user's account. I'd muc rather be able to do that when I go to create the review. Essentially I would like to do something like: systemAcct = models.ForeignKey(?, null=True, blank=True, on_delete=models.CASCADE) # Then my create method @classmethod def createReview(cls, **kwargs): review = cls.objects.get_or_create( campaign = kwargs['campaign'], manager = kwargs['manager'], employeeReviewed = kwargs['employeeReviewed'], reviewer = kwargs['reviewer'], systemAcct = kwargs['systemAcct'], ) I want … -
How to add multiple filters when using Django Rest framework search_filter
I'm currently trying to create a fullstack website using django for the backend. One of the features I'm building is a search function. To do that, I used the built in django-rest SearchFilter, as well as the built in OrderingFilter so users can toggle how results are ordered. However, I also want users to be able to filter their results further, such as selecting a specific year, or a specific name, from a drowdown menu. So essentially, I want to be able to use a search filter and still specify another field that has to match exactly. For example, lets say the users searched for "Cat" and the results were as follows: Name: Cat1 Description: A happy cat Year: 2017 Name: Cat2 Description: A sad cat Year: 2017 Name: Lion Description: A large cat Year: 2018 Name: Lion Description: A large cat Year: 2019 All of these results show up because they contain "cat" in either the name or description fields. But then, I want the user to be able to specify a year via a dropdown menu. So the menu would have 2017, 2018 and 2019 as options, and after selecting 2017, the results would be like this: Name: … -
Django def list API join two table drom DB
I am trying to use the def list function Django from these two which I have tables Batch and BatchYield the table of Batch look like batch_id | batch_status | `````````|```````````````| 11 | completed | and the table of BatchYield look like id | grade_a_produce | grade_b_produce | grade_c_rejection | harvest_date | batch_id | ```|`````````````````|`````````````````|```````````````````|``````````````|``````````| 23 | 100 | 120 | 212 | 22-02-12 | 11 | 25 | 110 | 122 | 242 | 21-01-14 | 11 | So I wrote a def list function in Django in which I have joined these two table with this code def list(self, request, *args, **kwargs): try: for data in request.data: batch_id = data.get('batch_id') all_batchyield = BatchYield.objects.filter(batch_id=batch_id).values('grade_a_produce', 'id', 'grade_b_produce', 'grade_c_rejection', 'harvest_date', 'batch_id') if all_batchyield.count == 0: return Response({"response": "Data not Found"}, status=status.HTTP_200_OK) all_batchyield_df = pd.DataFrame(all_batchyield) all_batchyield_df = all_batchyield_df.replace({np.nan: None}) all_completed_batchs = Batch.objects.filter(id=batch_id).values('batch_status', 'id') completed_batch_df = pd.DataFrame(all_completed_batchs) completed_batch_df = completed_batch_df.replace({np.nan: None}) completed_batch_df.rename(columns={'id': 'batch_id'}, inplace=True) final = pd.merge(completed_batch_df, all_batchyield_df, on='batch_id') final = final.drop('batch_id', axis=1) except Exception as e: return Response({"response": str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(final.to_dict('record'), status=status.HTTP_200_OK) From this code I got the and output which look like this [ { "batch_status": "completed", "grade_a_produce": 100.0, "id": 23, "grade_b_produce": 120.0, "grade_c_rejection": 212.0, "harvest_date": "2022-02-12T00:00:00Z" }, { "batch_status": … -
Django Not Recognizing Valid SuperUser
I am writing an app called product using django and I created a superuser for it, but it won't recognize the newly created super user. It will recognize the super user from another app I created, and that app and all it's related file are resting in a different directory all together. I've Made sure that both users that I added had the correct flags checked Here's what the settings.py looks like """ Django settings for inventory_app project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-qoi+29i4s@c@gw)6uoy!xja!6q)=1g=s05yja$mrlwlo_ht%vd' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'productapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'inventory_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
RuntimeError: no running event loop Djnago runworker
I am deploying my Django app on AWS Ec2 with Apache. I have Asgi and WSGI. I wanna run: sudo daphne MyProject.asgi:channel_layer --port 80 --bind 0.0.0.0 -v2 sudo python manage.py runworker -v2 But when I run the worker I am getting Running worker for channels ['channels'] Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/lib/python3.8/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/lib/python3.8/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3.8/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3.8/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/ubuntu/.local/lib/python3.8/site-packages/channels/management/commands/runworker.py", line 46, in handle worker.run() File "/usr/lib/python3.8/asgiref/server.py", line 59, in run event_loop = get_running_loop() RuntimeError: no running event loop I found this solution: Daphne + Channel v3 Deployment, RuntimeError: no running event loop but I already have asgiref==3.3.4 1-I found this one on github: https://github.com/django/asgiref/issues/278 but did not really understand how should I solve it. 2-I also did not really understand what should I do in Apache to filter the websocket request from the Normal request. If anyone has the same problem and know how to do it I would really appreciate it. Cause I don't have any Idea how to … -
Get primary key of specific object from list of objects in Django
I am trying to get the specific pk of the selected object when the user accepts a delivery. My problem is that I'm getting only the first object's pk in the list every time. I want to get the pk of the selected object. views: @login_required(login_url="/signin/?next=/driver/") def deliveries_available_page(request): deliveries = Delivery.objects.filter( status_of_delivery__in=[Delivery.DELIVERY_POSTED] ) #When driver accept delivery then status of delivery changes to delivering if request.method == 'POST': delivery = get_object_or_404(Delivery, pk=request.POST.get('receipt_number')) if delivery: delivery.status_of_delivery = Delivery.DELIVERY_DELIVERING delivery.driver = request.user.driver messages.success(request, 'Delivery Accepted') delivery.save() return redirect(reverse('driver:deliveries_available')) return render(request, 'driver/deliveries_available.html', { "GOOGLE_API_MAP": settings.GOOGLE_API_MAP, "del": deliveries }) HTML: <div class="d-flex flex-column h-100" style="padding-bottom: 50px"> <div id="map"></div> {% if del %} {% for d in del %} <div class="card" id="delivery-popup"> <div class="card-body p-2"> <div class="details"> <div class="p-2"> <strong id="address"></strong> <div> <strong id="show-info"></strong> </div> <div> <strong id="show-distance"></strong> <strong id="show-duration"></strong> </div> <div> <strong id="show-price"></strong> <strong id="show-id"></strong> </div> <div> <form method="POST"> {% csrf_token %} <button type="submit" class="btn btn-primary" name="accept">Accept</button> <input type="hidden" value="{{ d.receipt_number }}" name="receipt_number"> </form> </div> {% if messages %} {% for m in messages %} {% if m.tags %} <script>alert("{{ m }}")</script> {% endif %} {% endfor %} {% endif %} </div> </div> </div> </div> {% endfor %} {% endif %} I need the … -
How can django post multiple values at once?
If you create a code like above, create a value in index.html, and press the button to print only one value. How can I solve this problem? if request.method == 'POST': post = Post() post.yyyy = request.POST['yyyy'] post.mm = request.POST['mm'] post.dd = request.POST['dd'] post.cookname = request.POST['cookname'] post.save() global post_list post_list = { 'yyyy':post.yyyy, 'mm':post.mm, 'dd':post.dd, 'cookname':post.cookname } return redirect('index') else: post = Post.objects.all() return render(request, 'dncapp/index.html', {'post':post})``` -
Getting all objects of a model with ForeignKey field results in slow and a lot of query calls
When using the ModelChoiceField I am passing all the objects via brand = forms.ModelChoiceField(queryset=MobileModel.objects.all()) The model is as follows: class MobileModel(models.Model): brand = models.ForeignKey(MobileBrand, on_delete=models.PROTECT, blank=True, null=True) .... When checking with the debugger I see SQL query is called for every mobile model rows for getting the brand. Which for large records ends up with huge SQL queries. How to solve it and reduce the foreign key SQL queries. -
Django - Use field value as param in KeyTextTransform
Trying to use KeyTextTransform to grab a number from a json field. Only problem is, the target number is nested under a user_id. In order to grab the number, I need to dynamically grab the user_id, and use the user_id to key into the target dictionary. So my question - How can I pass the value of a field into KeyTextTransform? book \ .annotate(buyer_id=KeyTextTransform('selected_user', 'sale')) \ .annotate(price=KeyTextTransform(F('buyer_id'), 'sale')) # does not work -
Video stored in Firebase not playing in Iphones
I have a 5 Mb .mp4 video in firebase storage, using the below code it loads well in all web browsers. However it does not load in iPhone. .mp4s didn't work in safari but .mov did. However both .mp4 and .mov do not work on an iPhone. What can I do or video format to use? <video width='100%' height='315' poster='{{ value.image }}' controls loop muted playsinline> <source type='video/mp4' src='{{ value.video }}'> </video> -
Django redundant user relation in related models for permission purposes
I am pretty new to django and backend, I made two models Car & Service which have a relation to user (to check permissions, while operating on them) and now I am trying to relate one with another, I have noticed they have both user relation, but Service can't exists without Car, so I start wondering if there is any sense of having user relation in Service just for permissions puroposes, or is it better to create separete permissions for every Model: Car Model: class Car(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) ... and Service Mode: class Service(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) car = models.ForeignKey( "cars.Car", on_delete=models.CASCADE, related_name="services", ) and permission used in both API views for those models: class isAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.user == request.user What would be your advice in this scenario ? -
upload shape file in geodjango
i am Trying to upload a shape file to postgres by django and geopandas. but it return this error: (psycopg2.errors.DuplicateTable) relation "idx_Village_kcnT1Uu_geom" already exists this is my model: class ShapeFile(models.Model): name = models.CharField(max_length=45) description = models.TextField() file = models.FileField(upload_to='user_shape_file') date = models.DateTimeField(auto_now_add=True) and i am using this signal to upload it: @receiver(post_save, sender=ShapeFile) def post_save_r(instance, **kwargs): file = instance.file.path file_format = os.path.basename(file).split('.')[-1] file_name = os.path.basename(file).split('.')[0] file_path = os.path.dirname(file) name = instance.name connection = 'postgresql://postgres:1234@localhost:5432/geoapp' with zipfile.ZipFile(file, 'r') as opened_zip: opened_zip.extractall(file_path) shape_file = glob.glob(r'{}/**/*.shp'.format(file_path), recursive=True)[0] gfr = gpd.read_file(shape_file) epsg = 4326 engine_ = create_engine(connection) gfr['geom'] = gfr['geometry'].apply(lambda x: WKTElement(x.wkt, srid=epsg)) gfr.to_sql(name, engine_, 'public', if_exists='replace', index=False, dtype={'geom': Geometry('Geometry', srid=epsg)}) but it return this error: -
Deploying Django to production correct way to do it?
I am developing Django Wagtail application on my local machine connected to a local postgres server. I have a test server and a production server. However when I develop locally and try upload it there is always some issue with makemigration and migrate e.g. KeyError etc. What are the best practices of ensuring I do not get run into these issues? What files do I need to port across? -
Django model instance default value
I have Django model name = models.CharField(max_length=255) excerpt = models.TextField() desc = models.TextField() due_date = models.DateTimeField() created_at = models.DateTimeField() priority = models.IntegerField(default = 1) When I create model instance, I want to set priority value to maximum value among all instances incremented by one. (max(priority)+1). Thank you. -
Crispy Forms - How to pass a helper to both a form and a formset?
I'm using Csripy Forms to render a formset and I'd like to use a helper to modify the forms themselves. How do I pass both the form helper and the formset helper to the crispy tag? My form class ModelForm(ModelForm): class Meta: model = MyModel exclude = ['key'] labels = { 'name': 'Stage', } The formset class ModelFormSetHelper(FormHelper): # see https://django-crispy-forms.readthedocs.io/en/latest/layouts.html def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_tag = False self.layout = Layout( Row( Column('name', css_class='col'), Column('conversion_rate', css_class='col-md-3 col-4'), css_class='formset-row' ) ) self.disable_csrf = True My tag {% crispy mymodel_formset formset_helper %} -
how to enable prometheus custom metrics for Django backend process (realtime kafka consumer) and access web endpoint
I have django app for kafka consumer which consumed realtime events and I have added custom prometheus metrics to track consumed events but when my app is running i don't see custom metrics at the web endpoint /metrics. I am getting 504 gateway timeout error because my consumer is running in the background and no response gets send out. I tried with Django health check but its the same issue. I tried running my consumer using Django custom management command, but then web endpoint didn't work. So is there a way to run consumer app in background and exposed prometheus metrics and access web endpoint -
Return the response from ListCreateAPIView
I want to return the custom json response after perform_create class MyObjList(generics.ListCreateAPIView): def get_serializer_class(self): if self.request.method == 'GET': return MyObjListSerializer return MyObjCreateSerializer def perform_create(self, serializer): // do something here. return Response({'isDraft': 1}) class MyObjCreateSerializer(serializers.Serializer): class Meta: fields = ('answer') However this dosen't return the any response,for my Javasctipt axios.post(API_URL, data, config).then(({ data }) => { console.log(data); // just show {} }).catch(error => { console.log(error); }); What I want to do is create object in perform_create and return the keyname to the client. However currently in my code it doesn't return anything. I wonder if Serializer class is relevant, but I am not sure the role of serializer class for POST> -
Django ORM bulk_update
I have stuck on this task. I have Professor model and i need to update from 2 queries but i have 6 queries in my DB. from django.db import models class Professor(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField(default=18) My function. def update_professor_first_names(): first_name_updates = [(1, 'freddie'), (2, 'mady'), (3, 'hady'), (4, 'michael'), (5, 'rose')] tmp = [] for prof_id, new_first_name in first_name_updates: prof = Professor.objects.get(id=prof_id) prof.first_name = new_first_name tmp.append(prof) Professor.objects.bulk_update(tmp, ['first_name']) Please give me some advices. -
how to serialize data with python after getting it from firebase in django?
i'm working with Django and i want to retrieve data from firebase and make it readable and serializable when retrieving data from the default database (sqlite) i use this function : @api_view([('GET')]) def getPatients(request): patients = Patient.objects.all() serializer = PatientSerializer(patients , many = True) return Response(serializer.data) i want to change this function to get and serialize the data from firebase . i tried to get data from firebase and send it in the response but it is not showing in the web view page . the solution i tried : @api_view([('GET')]) def getPatients(request): patients = database.child('patients').get().val() serializer = PatientSerializer(patients , many = True) return Response(serializer.data) -
pipenv install django fail
I am using pipenv to install django, but I get an Error. Usage: pipenv install [OPTIONS] [PACKAGES]... ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting. -
Django / Python - change does not save in database - AttributeError: 'QuerySet' object has no attribute 'reload'
I have a setting that a user can change: send email automatically or manually. For this, I created a database with only 1 row that has the following columns: class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") def get(self): new_self = self.__class__.objects.get(pk=self.pk) # You may want to clear out the old dict first or perform a selective merge self.__dict__.update(new_self.__dict__) return reverse("core:autosend", kwargs={"auto": self.auto}) def reload(self): new_self = self.__class__.objects.get(pk=self.pk) # You may want to clear out the old dict first or perform a selective merge self.__dict__.update(new_self.__dict__) In this, either 'auto' or 'manual' is True, and the other one is False. The 'type' is set to 'auto' or 'manual' accordingly. This setting is used in the rest of the code. The code I have now in my view is: class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} model = AutoSendMail.objects.get(id=1) model.refresh_from_db() autoSetting = int(model.auto == True) manualSetting = int(model.manual == True) def post(self, request, *args, **kwargs): id_ = self.kwargs.get("pk") update_type = self.request.POST.get('update_type') if update_type == 'manual': logger.info("Set to: manual email send") model = AutoSendMail.objects.filter(id=1) model.manual = True model.auto = False model.type = "manual" for object …