Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the Django ORM not saving my objects
I created a simple blog with DRF and vue. When trying to save my Category & Tag Models Django returns objects with a null id. However, when trying to save my post objects it works fine. Does anyone know what I'm doing wrong here? class Category(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True, null=False) posts = models.ManyToManyField(Post, related_name='categories', blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): # new if not self.slug: self.slug = slugify(self.name) After I create the model I don't expect the id, but once I save the model the ID should show. Here's the manage.py shell I get the same thing if I put it through the following serializer. class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = [ 'id', 'name', 'slug' ] I'm getting the same data back with I call my viewset endpoint as well. How do I go about getting django to generate the id's and save the models? I've tried to do it manually as well (after recreating the test db) and the results were the same. I've also tried deleting and rebuilding the migrations from scratch. For reference here is the post model class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) title = … -
Admin page not opening?
TypeError at /admin/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 4.0.1 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: E:\Django Project\Ecom\venv\lib\site-packages\django\urls\resolvers.py, line 494, in _populate Python Executable: E:\Django Project\Ecom\venv\Scripts\python.exe Python Version: 3.9.6 Python Path: ['E:\Django Project\Ecom', 'C:\Python39\python39.zip', 'C:\Python39\DLLs', 'C:\Python39\lib', 'C:\Python39', 'E:\Django Project\Ecom\venv', 'E:\Django Project\Ecom\venv\lib\site-packages'] Server time: Thu, 27 Jan 2022 15:56:51 +0000 -
Django: Parameterized expand with newly created model object doesn't work
I am trying to test some django code. I want to use parameterized.expand to provide newly created Boat model objects to the method named test_method I create these model objects Boat in the test class's setUp method. My (flawed) understanding is the following: MyTestClass.setUp is run and it creates the Boat objects into the test database test_method is run for each group of variables in the parameterized decorator. Note, the parameterized decorator references the newly created Boat objects. What actually happens: parameterized decorator is instantiated at build time, before setUp is run an error is thrown because there are no Boat objects (because setUp hasn't run yet`) Here is the code: from core.models import Boat from parameterized import parameterized class MyTestClass: def setUp(self): Boat.objects.create() @parameterized.expand( [ [[Boat.objects.all()], 1], ] ) def test_method(self, list_of_boats, expected_number_of_boats]): assert len(list_of_boats] == expected_number_of_boats I get the error sqlite3.OperationalError: no such table: core_boat How do I use newly created model objects with parameterized.expand? -
Django supervisord and apscheduler
In Django project, have a supervisord than start apscheduler [program:apscheduler] command=/home/user/Project/.venv/bin/python manage.py runapscheduler In apscheduler I have one job: # runapscheduler.py import logging import sys from django.conf import settings from django.core import management from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.triggers.cron import CronTrigger from django.core.management.base import BaseCommand from django_apscheduler.jobstores import DjangoJobStore from django_apscheduler.models import DjangoJobExecution from django_apscheduler import util logger = logging.getLogger(__name__) def my_management_command(): management.call_command('MyCommand') # The `close_old_connections` decorator ensures that database connections, that have become unusable or are obsolete, # are closed before and after our job has run. @util.close_old_connections def delete_old_job_executions(max_age=604_800): """ This job deletes APScheduler job execution entries older than `max_age` from the database. It helps to prevent the database from filling up with old historical records that are no longer useful. :param max_age: The maximum length of time to retain historical job execution records. Defaults to 7 days. """ DjangoJobExecution.objects.delete_old_job_executions(max_age) class Command(BaseCommand): help = "Runs APScheduler." def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( my_management_command, trigger=CronTrigger(hour="*", minute="*"), # Every hour id="MyCommand", # The `id` assigned to each job MUST be unique max_instances=1, replace_existing=True, ) logger.info("Added hourly job 'my_management_command'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="00", minute="00" ), # Midnight on Monday, before start of the next work week. … -
Python class variable usage across thread have different value
I'm getting confused about class variable access through multi-thread. I'm in a django application and I initialize a class at server startups to inject some configuration. Then on user requests I call some method on that class but the config is None. class SharedService: _queue_name = None @staticmethod def config(queue_name=None): if queue_name: SharedService._queue_name = queue_name print(SharedService._queue_name) # this print the "alert" @staticmethod def send_message(data): print(SharedService._queue_name) # this print None if usefull in the django settings class loaded at startup I do: SharedService.config(queue_name="alert") and in the user endpoint I just call: SharedService.send_message("blabla") I'm sure it did work previously, but we did update to python 3.10 and django 3.2 recently and might be related (or not!) -
How to group multiple functions for parallel execution with Celery?
I wanted to group multiple functions for parallel execution in Django within the transaction.on_commit function -however, I got TypeError: cannot unpack non-iterable int object I have tried to resolve this, but I now think I'm misusing one of the args. This was my initial approach: # tasks.py def func_a(keys: tuple, link_set: dict): # keys contain random integers as pk return def func_b(keys: tuple, link_set: dict): return def func_c(keys: tuple, link_set: dict): return I tried to call these in my signal like this: @receiver(post_save, sender=Foo) def start_task(sender, instance, created, **kwargs): if created: ... keys = (instance.pk, foo.pk) link_set = {} transaction.on_commit(lambda: group([ tasks.func_a.si(keys, link_set), tasks.func_b.si(keys, link_set), tasks.func_c.si(keys, link_set) ]).delay()) The 3 functions in tasks.py are independent of each other with no return value, putting them together into one incurs a little cost that I'd like to avoid- how best can I compose these functions for a faster response? Thanks -
Django many-to-many override save method to increment a field instead of creating new objects
I have the following classes in my Models.py: class Size(models.Model): prod_size = models.DecimalField(max_digits=3, decimal_places=1) quantity = models.IntegerField(default=1) def save(self, *args, **kwargs): size_exists = Size.objects.filter( prod_size=self.prod_size, product_id=self.product_id ).exists() if size_exists: Size.objects.filter( prod_size=self.prod_size, product_id=self.product_id ).update(quantity=F('quantity')+1) else: super(Size, self).save(*args, **kwargs) class Product(models.Model): sizes = models.ManyToManyField(Size, related_name='products') I want the save method to update the quantity field of Size if there already exists a prod_size with the same value and related to the same product_id. But I am having trouble with getting the product_id information from the intermediate table. Is there any way I can achieve this? -
Deploying a Django application to Elastic Beanstalk AWS 502 Bad Gateway
I follow all the instructions on the official AWS website, but I still get the same mistake. I have tried several projects, each on the local server works quite normally as soon as it starts on AWS I get the next error 502 Bad Gateway. this seams like main problem : ModuleNotFoundError: No module named 'ebddjango/wsgi' Status: Updated: 2022-01-27 14:19:09.259000+00:00 Status: Ready Health: Red Erorr log Jan 27 14:49:19 ip-172-31-8-170 web: File "", line 1006, in _gcd_import Jan 27 14:49:19 ip-172-31-8-170 web: File "", line 983, in _find_and_load Jan 27 14:49:19 ip-172-31-8-170 web: File "", line 965, in _find_and_load_unlocked Jan 27 14:49:19 ip-172-31-8-170 web: ModuleNotFoundError: No module named 'ebddjango/wsgi' Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4399] [INFO] Worker exiting (pid: 4399) Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4392] [INFO] Shutting down: Master Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4392] [INFO] Reason: Worker failed to boot. Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Starting gunicorn 20.1.0 Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Listening at: http://127.0.0.1:8000 (4407) Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Using worker: gthread Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4414] … -
How to set up a loading screen for a form that takes time to process in Django?
I have the following view (with some code removed for simplicity): def add_entry(request, num): form = ModelForm1() form2 = Form2() if request.method == 'POST': form = ModelForm1(request.POST) form2 = Form2(request.POST) if form.is_valid() and form2.is_valid(): text = form2.cleaned_data['text'] database_dict = process_data(text) # Some code here that dictates how data is saved from the dictionary.... entry.save() return redirect('entries', num) return render(request, 'app/add_entry.html', {"form": form, "form2": form2}) Basically, this view contains a form which takes a text input. That text input is processed through a function with returns a dictionary of values. Those values are then stored in a database, and this database is rendered to the template "entries.html". Depending on the amount of text in the form, it can take quite some time to process, and this time is spent in the input-screen of the form. I would like to add an interim "loading"-screen which the user is taken to while the form is processed, which then redirects to entires.html after the processing is done, but I can't seem to find out how. Adding a redirect without the "return" statement right after the data is processed doesn't seem to do anything, and adding the "return" messes everything up. How do I do … -
simple: django create dynamic url
When your view looks like this def LinkView(request): #do i even have to pass parameters to the function? return render(request, 'linkview.html', {}) What can I do to have a dynamic URL based on the user model so that every user has his own url/page? path('links/#User_model??#/', LinkView), -
Django Rest Framework ModelViewSet ManyToMany Field override partial_update Method is not working update_or_create
I have a question here I have two models Tag Model class Tag(models.Model): creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author') name = models.CharField(max_length=100) def __str__(self): return self.name Profile Model class Profile(models.Model): profiler = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='contour') bio = models.TextField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, related_name='keywords') image = models.ImageField(default='avatar.jpg', upload_to='images', blank=True, null=True) def __str__(self): return f'{self.profiler}' Tag Serializer class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' Profile Serializer class ProfileSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, read_only=True) class Meta: model = Profile fields = ['id', # List All fields Exclude profiler => OneToOne field name 'bio', 'description', 'tags', 'image', 'birthDate', 'created', 'updated', ] depth = 1 Profile Viewset class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = [IsAuthenticated] def partial_update(self, request, *args, **kwargs): data = request.data profile_obj = Profile.objects.update( profiler=self.request.user, bio=data['bio'], description=data['description'], image=data['image'], birthDate=data['birthDate'], ) profile_obj.save() for tag in data['tags']: tag_obj = Tag.objects.update_or_create( creator=self.request.user, name=tag['name'], # name => Field Name in Tag Model ) print(tag_obj) profile_obj.tags.add(tag_obj) # tags => ManyToMany Field Name in Profile Model serializer = ProfileSerializer(profile_obj) return Response(serializer.data) my aim is to create a new tag if this name is not exist, and also update profile tags but my code is not working, and I don't know why Can Any body … -
How to add data to Many-To-Many field in Django DRF
I'm new to Django DRF, trying to have a sports school project done. I have a model for coaches, classes and students. Here is a stripped version to keep it simple and easy: class Student (models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) def __str__(self): return f'{self.first_name} {self.last_name}' class Coach (models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) def __str__(self): return f'{self.first_name} {self.last_name}' class ClassDetails (models.Model): class_name = models.CharField(max_length = 50) class_coach = models.ForeignKey(Coach, related_name='coach_classes') class_members = models.ManyToMany(Student, related_name='student_classes') def __str__(self): return self.class_name In order to list/add students to the class, I'm using the following serializer: class ClassDetailsSerializer(serializers.ModelSerializer): class Meta: model = ClassDetails fields = ['id','class_name', 'class_coach', 'class_members] read_only_fields = ('id', 'class_name', 'class_coach') Getting the data is working ok. Also, adding a coach is working fine, what is really giving me a hard time is adding a class member. I'm using the following view: def member_add(self, request): my_class = ClassDetails.objects.get(pk = request.data['id'] serializer = ClassDetailsSerializer(my_class, data=request.data) if serializer.is_valid(): serializer.save() return Response('Member added', status.HTTP_201_CREATED) return Response(serializer.errors, status.HTTP_406_NOT_ACCEPTABLE) I'm sending a POST body like: { "id": 2, <- class id "class_members": [20] <- student's id to add to the class members } The problem is no … -
Comment je dois regler ce probleme dans mon code'NoneType' object has no attribute 'is_admin'
from django.db import models from django.contrib.auth.base_user import AbstractBaseUser,BaseUserManager class UsagerManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Vous devez entrer un mail valide ou un téléphone valide") user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save() return user def create_superuser(self, email, password = None): user = self.create_user(email=email, password=password) user.is_admin = True user.is_staff = True user.save() return user class UsagerClient(AbstractBaseUser): CHOISI = [ ('Atl', 'Atlantique'), ('Ata','Atacora'), ('Ali', 'Alibori'), ('Bor', 'Borgou'), ('Cou', 'Couffo'), ('Col', 'Colline'), ('Don', 'Donga'), ('Lit', 'Littoral'), ('Mon', 'Mono'), ('Oue', 'Oueme'), ('Pla', 'Plateau'), ('Zou', 'Zou') ] nom = models.CharField(max_length=50) prénom = models.CharField(max_length=100) téléphone = models.CharField(max_length=8) societe = models.CharField(max_length=15) email = models.EmailField(unique=True, max_length=255, blank=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) département = models.CharField(max_length=30, choices=CHOISI) ville = models.CharField(max_length=3) adresse = models.CharField(max_length=50) USERNAME_FIELD = "email" objects = UsagerManager() REQUIREMENT_FIELD = ["nom", "prénom", "téléphone", "email", "département","ville", "adresse"] def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True -
Reference the parent model id in getting the child data in Django Multitable inheritance
I have extended 2 models from a parent model like this. class ParentModel(models.Model): # fields class ChildModelA(ParentModel): # fields class ChildModelB(ParentModel): # fields Is there any way I can reference the id of the child models to the parent model? Right now, I am still manually fetching it by obj.parentmodel_ptr.id -
Respond to Instagram webhook in Django
I set the callback-url for Instagram webhook, and when Instagram Get my callback-url I should Respond to the hub.challenge to verify. Instagram GET request to my endpoint URL: GET https://callback_url/webhooks? hub.mode=subscribe& hub.challenge=1158201444& hub.verify_token=meatyhamhock But I have this error: The URL couldn't be validated. Response does not match challenge, expected value="1120110039", received="\u003C!DOCTYPE html>\n\u003Chtm..." My code in vews.py: def getInstagramWebhook(request): if request.method == "GET": mode = request.GET.get("hub.mode") challenge = request.GET.get("hub.challenge") verify_token = request.GET.get("hub.verify_token") return challenge I tried JsonResponse, HttpResponse, and redirect but not work -
Namespace Error uploading an image from Flutter Image Picker to Rest API using Django Rest Framework
I am receiving Namespace error in my debug console when I try to upload an image in Flutter through Django Rest Framework. The following code has been implemented: File? galleryFile; final ImagePicker _picker = ImagePicker(); Future imageSelectorGallery() async { var image = (await _picker.pickImage( source: ImageSource.gallery, )); if (image != null) { setState(() { galleryFile = File(image.path); }); List<int> imageBytes = galleryFile!.readAsBytesSync(); String baseimage = base64Encode(imageBytes); print(baseimage); } The error image: Any help would be appreciated. -
Django pass id from instance to not instantiated model field
Im my ProductImages model i made some fields to store various types of some image, like: models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) #This field is used in form image_file_w200_png = models.ImageField( verbose_name = "Selecione a imagem", upload_to=upload_to_image_file_w200_png, null=True, blank=True, default='magickhat-profile.jpg' ) #This field is not used in forms image_file_w480_png = models.ImageField( upload_to=upload_to_image_file_w480_png, null=True, blank=True, default='magickhat-profile.jpg' ) ... Well, the ideia is when user upload a image from image_file_w200_png field, the image is resized to various dimensions, and i save that other images in other fields like image_file_w480_png My actual problem consiste in upload_to, as we can see in docs, upload_to may also be a callable, such as a function. So i made my own function in utils.py to upload_to to each field. utils.py def upload_to_image_file_w200_png(instance, filename): ext = filename.split('.')[-1] filename = instance.product.slug+"_"+str(instance.id)+"_w200_png."+ext return 'user_{0}/{1}/{2}/{3}'.format(instance.product.user.id, instance.product.id, instance.id, filename) def upload_to_image_file_w480_png(instance, filename): ext = filename.split('.')[-1] filename = instance.product.slug+"_"+str(instance.id)+"_w480_png."+ext return 'user_{0}/{1}/{2}/{3}'.format(instance.product.user.id, instance.product.id, instance.id, filename) the problem is, instance.id is the id of field image, but the only field that is instantiated is image_file_w200_png field, the image_file_w480_png is not, so how can i use the instance.id from upload_to_image_file_w200_png function in upload_to_image_file_w480_png function? -
How to add row in automatically created table in Django from views.py?
I have a model called 'Kategoria' which is a ManyToMany field in 'Produkt' model: kategoria = models.ManyToManyField(Kategoria) Django automatically generated a table, which looks like this: In a view, I have retreived kategoria_id and created an object which is named "Produkt" in models.py. kategoria_nazwa = str(data['kategoria']) kategoriaa = Kategoria.objects.get(nazwa_kategorii=kategoria_nazwa) product = Produkt.objects.create(nazwa=nazwa, numer_partii=numer_partii, cena=cena, opis=opis, liczba=liczba, image=image, producent_id=producent_id) It is created successfully, however now I want to add information about product_id and kategoria_id to automatically generated table in django, which I obviously didn't declare in models.py file. # TODO: Produkt.kategoria.create(produkt_id=product.id_produktu, kategoria_id=kategoriaa.id_kategorii) This part doesn't work. It says that there is an AttributeError: 'ManyToManyDescriptor' object has no attribute 'create'. How to insert row into a table from views.py? I have also checked if kategoriaa.id_kategorii and product.id_produktu are correct, and everything is fine. -
Problem with TableOfContent ReportLab doc.notify does not generate in TOC
I have a problem with TableOfContent ReportLab doc.notify does not generate in TOC. Direct call to doc.notify does not generate in TableOfContent. Calling afterFlowable(doc, f) to definition does not generate a TableOfContent. Only direct doc.notify call in myLaterPages definition works, but of course it generates list of all pages with static string "Chapter". Where do I go wrong? from django.http import FileResponse from reportlab.pdfgen import canvas import reportlab.pdfgen from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak #from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch from django.http import HttpResponse, HttpResponseBadRequest from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import mm, inch from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.pdfmetrics import registerFontFamily from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus.tableofcontents import TableOfContents, SimpleIndex #from reportlab.lib.pagesizes import letter, A5 from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT PAGESIZE = (140 * mm, 216 * mm) BASE_MARGIN = 5 * mm def generatePDF(request,id): pdfmetrics.registerFont(TTFont('Berylium', 'resources/fonts/Berylium/Berylium.ttf')) pdfmetrics.registerFont(TTFont('BeryliumBd', './resources/fonts/Berylium/Beryliumbold.ttf')) pdfmetrics.registerFont(TTFont('BeryliumIt', './resources/fonts/Berylium/BeryliumItalic.ttf')) pdfmetrics.registerFont(TTFont('BeryliumBI', './resources/fonts/Berylium/BeryliumboldItalic.ttf')) registerFontFamily('Berylium', normal='Berylium', bold='BeryliumBd', italic='BeryliumIt', boldItalic='BeryliumBI') PAGE_HEIGHT=defaultPageSize[1] PAGE_WIDTH=defaultPageSize[0] book = Book.objects.get(id=id) Title = book.title pageinfo = book.title Author = book.author Filename = book.title def afterFlowable(self, flowable): "Registers TOC entries." if flowable.__class__.__name__ == 'Paragraph': text = flowable.getPlainText() style = flowable.style.name if style == 'style1': self.notify('TOCEntry', (0, text, self.page … -
Django create correct model form?
When I load the page, the value of the input is automaticly this: How is that possible? views file if request.method == 'POST': form = FieldForm(request.POST, instance=Field(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard') else: form = FieldForm(instance=Field) ...... forms file class FieldForm(forms.ModelForm): class Meta: model = Field fields = ( 'title', 'url' ) models file class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=255) url = models.CharField(max_length=255) creator_adress = models.GenericIPAddressField(null=True) def __str__(self): return str(self.user) Here one input 😂 " maxlength="255" required="" id="id_url"> -
Table already exists when I run pytest on Django project
I have a Django project of version 3.2.5. I created a new model: app.model. Then I ran python manage.py makemigrations app command. When I ran the tests via pytest, I got the following errors: E psycopg2.errors.DuplicateTable: relation "app_model" already exists E django.db.utils.ProgrammingError: relation "app_model" already exists However there's no such table neither on my local database nor in test database which is created from scratch. I pushed my code on a branch to Github and build succeeded online with no problems. However my test suite complained about this existing table. I ran python manage.py migrate app and it worked. -
How to use SMTP to send email using python on Godaddy servers
I have build a website using django,and it uses smtp to send me a mail containing details filled out on a form on the same site,But SMTP is not working on Godaddy servers,Below is the code i used: import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMETe sender_address = 'user@gmail.com' receiver_address = 'userto@gmail.com' sender_pass = '123' #Setup the MIME message = MIMEMultipart() message['From'] = sender_address message['To'] = receiver_address message['Subject'] = 'N' #The subject line #The body and the attachments for the mail message.attach(MIMEText(mail_content, 'plain')) #Create SMTP session for sending the mail session = smtplib.SMTP('localhost', 25) #use gmail with port session.starttls() #enable security session.login(sender_addres, sender_pass) #login with mail_id and text = message.as_string() session.sendmail(sender_address, receiver_address, text) session.quit() print('Mail Sent') it just gives me the error: SMTPAuthenticationError (535, b'Incorrect authentication data') My username and password are correct,i have used localhost and port 25 as said in one of thier documentation Thanks in Advance -
How to use another python project function into your project
I'm working with Django in a project, I want to use a python function from a project in Github, I can't install this project as a library with pip install dicom-exporter because it doesn' work. The project I want to use: https://github.com/KitwareMedical/dicom-exporter/ the function I want to use : dicom-exporter <path/to/dicom/folder> <path/to/output.vti> The project contain setup.py file where there is script entry-point, Please How can use this project in my django project. -
What should I do so that the result of filter() function is the dictionary mapping result
I have a model like this: class BNetworkEdge(models.Model): id = models.AutoField(unique=True, primary_key=True) source = models.IntegerField() target = models.IntegerField() edge_type = models.IntegerField() class Meta: managed = True db_table = 'b_network_edge' I have a dictionary like this: {0:'direct', 1:'no-direct'} How do I get the function 'BNetworkEdge.objects.all()' is directly the dictionary mapping result? Thanks! -
Delete django data without RuntimeWarning: DateTimeField received a naive datetime
I am trying to delete 3 years old data in my python django db. Here is code: from datetime import datetime from dateutil.relativedelta import relativedelta def db_cleanup(): cleanup_start = datetime.utcnow().date() three_years_ago = cleanup_start - relativedelta(years=3) MyData.objects.filter(create_date__lt=three_years_ago).delete() however I receive RuntimeWarning: DateTimeField received a naive datetime . How to do it properly?