Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i can not get in varartionb in command line
in my e comerce project i want to create variations for the products and here is my entire code model.py from django.db import models from catagory.models import catagory from django.urls import reverse # Create your models here. class Product(models.Model): product_name = models.CharField(max_length=200,unique=True) slug = models.SlugField(max_length=200,unique=True) description = models.TextField(max_length=500,blank=True) price = models.IntegerField() image = models.ImageField(upload_to='photos/Product') stock = models.IntegerField() is_available= models.BooleanField(default=True) catagory = models.ForeignKey(catagory,on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name def get_url(self): return reverse('product_detial',args=[self.catagory.slug,self.slug]) class VariationManager(models.Manager): def colors(self): return super(VariationManager,self).filter(varation_category='color',is_active=True) def sizes(self): return super(VariationManager,self).filter(varation_category='size',is_active=True) varation_category_choice =( ('color', 'color'), ('size', 'size'), ) class Variation(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) varation_category = models.CharField(max_length=100,choices= varation_category_choice) varation_value = models.CharField(max_length=100) is_active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now = True) objects = VariationManager() def __str__(self): return self.varation_value views .py def add_cart(request,product_id): product = Product.objects.get(id=product_id) #product_varation=[] if request.method == 'POST': for item in request.POST: key = item value = request.POST[key] #print(key,value) try: varation = Variation.objects.get(varation_category__iexact=key,varation_value__iexact=value) print(varation) except: pass ..... and when i tray to add new product it added successfully but it dose not print the variation in the command line i don't know why it is not working please help me? -
apache wsgi_mod fails to run on python 3.10
I am developing a django app using django 4 and python 3.10. I had a server using apache and mod_wsgi, that used to run an old app using python3.8. I've created a virtual env from 3.10. Command line manage.py is working well. I've changed apache's conf: WSGIDaemonProcess my_app310 python-path=/home/ubuntu/my_app310:/home/ubuntu/venv/my_app310/lib/python3.10/site-packages WSGIProcessGroup my_app310 WSGIScriptAlias / /home/ubuntu/my_app310/my_app310/wsgi.py But I keep getting: [mpm_event:notice] AH00489: Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [core:notice] AH00094: Command line: '/usr/sbin/apache2' [wsgi:error] mod_wsgi (pid=1724834): Failed to exec Python script file '/home/ubuntu/my_app310/my_app310/wsgi.py'. [wsgi:error] mod_wsgi (pid=1724834): Exception occurred processing WSGI script '/home/ubuntu/my_app310/my_app310/wsgi.py'. [wsgi:error] Traceback (most recent call last): [wsgi:error] File "/home/ubuntu/venv/my_app310/lib/python3.10/site-packages/django/utils/timezone.py", line 10, in <module> [wsgi:error] import zoneinfo [wsgi:error] ModuleNotFoundError: No module named 'zoneinfo' Which suggest that something is running using python3.8 and not python3.10 (mod_wsgi?). What am I missing? -
django heroku, page content corruption after git push heroku master
Today I added images to my database on the heroku admin page. When I refreshed the Website, the page looked fine. But then when I did "git push heroku master" without making any changes in my current project, the content of my website got corrupted.what could be the reason for this? -
How to post record with pytest-django?
I want to write tests for the project using the pytest-django library. I have a "Context" model with "name"(Charfield) and "description" (Charfield) fields. I want to create a test record through the Django admin panel, but for some reason I can't ( class TestViewContext: def test_post_view_get(self, admin_client): name = 'Sometext' description = 'description' data={'name': name, 'description': description} response = admin_client.post( '/admin/book/context/add/', data=data ) post = Context.objects.filter(name=name, description=description).first() assert post is not None, 'Check new post' -
Docker-compose up command throwing Error while fetching server API version
ERROR: After running a command Docker-compose up It throwing such type of error Traceback (most recent call last): File "docker\api\client.py", line 214, in _retrieve_server_version File "docker\api\daemon.py", line 181, in version File "docker\utils\decorators.py", line 46, in inner File "docker\api\client.py", line 237, in _get File "requests\sessions.py", line 543, in get File "requests\sessions.py", line 530, in request File "requests\sessions.py", line 643, in send File "requests\adapters.py", line 439, in send File "urllib3\connectionpool.py", line 670, in urlopen File "urllib3\connectionpool.py", line 392, in _make_request File "http\client.py", line 1255, in request File "http\client.py", line 1301, in _send_request File "http\client.py", line 1250, in endheaders File "http\client.py", line 1010, in _send_output File "http\client.py", line 950, in send File "docker\transport\npipeconn.py", line 32, in connect File "docker\transport\npipesocket.py", line 23, in wrapped File "docker\transport\npipesocket.py", line 72, in connect File "docker\transport\npipesocket.py", line 52, in connect pywintypes.error: (2, 'CreateFile', 'The system cannot find the file specified.') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose\cli\main.py", line 81, in main File "compose\cli\main.py", line 200, in perform_command File "compose\cli\command.py", line 60, in project_from_options File "compose\cli\command.py", line 152, in get_project File "compose\cli\docker_client.py", line 41, in get_client File "compose\cli\docker_client.py", line 170, in docker_client File "docker\api\client.py", … -
Django rest framework datatables search error
I am using django-rest-framework-datatables and a connection with djongo to mongodb. I have a problem though using the search field. Could you help me please ? Thankyou! DatabaseError at /app/data/ Sub SQL: None FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "app_person"."id" AS Col1, "app_person"."Name" AS Col2, "app_person"."Surname" AS Col3, "app_person"."BirthDate" AS Col4, "app_person"."Sex" AS Col5 FROM "app_person" WHERE ("app_person"."Name" iLIKE %(0)s OR "app_person"."Surname" iLIKE %(1)s)) subquery Params: ('%A%', '%A%') I have the following code: views.py class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer .html $(document).ready(function() { $('#model').DataTable({ 'serverSide': true, 'stateSave': true, //restore table state on page reload, 'searching': true, 'ajax': '/app/data/?format=datatables', 'columns': [ {'data': 'Name', 'name': 'Name'}, {'data': 'Surname', 'name': 'Surname'}, {'data': 'BirthDate', 'searchable': false}, ] }); }); -
Django: retrieve data for a specific interval
I am going to build my dashboard. Design of this Dashboard is completed. Now the problem is that I did not understand how to retrieve my sum of data from database (mysql) with a specific interval. for example I want to retrieve revenue of last 15 days? how ?? models.py class JaGAnalyticsData(models.Model): project_management_id = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) ecommerce_users = models.FloatField(blank=True, null=True) total_revenue = models.FloatField(blank=True, null=True) conversion_rate = models.FloatField(blank=True, null=True) total_transactions = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'ja_g_analytics_data' views.py @login_required(login_url="/login/") def index(request): jga = JaGAnalyticsData.objects.all() #this line of code will fetch the data from db context = {'jga':jga} #html_template = loader.get_template('home/index.html') #return HttpResponse(html_template.render(context, request)) return render(request, 'home/index.html',context) index.html <div class="row"> <div class="col-sm-6"> <h5 style="margin-top:3px " class="card-title text-uppercase text-muted mb-0">Last week</h5> </div> <div class="col-sm-6"> {{% for i in a %}} <span style="float: right;" class="h4 font-weight-bold">{{i.total_revenue}}</span> {{% end for %}} </div> -
pip-list inside and outside environment give the same list
My question is very similar to this one : Powershell - Pip freeze inside virtual environment listing packages from global pip I'm developing a Django app. I suspect that despite having a virtual environment activated, I'm still working with the global system Python environment: pip-list (or python3 -m pip-list) give the same output whether or not the environment is activated. Same thing with pip freeze / python3 pip freeze. How could I be sure of it, and fix this if necessary? -
Django form at valid() stage failing Validation
I have created a html form which is linked to a django form. When the html form data is passed to the django form it fails at the is form.is_valid():. I think its to do with the formatting but i have read the docs and cant find a solution. form.py class AvailabilityForm(forms.Form): name = forms.CharField(max_length=80, required=True) email = forms.EmailField(max_length=254, required=True) start_date = forms.DateField(input_formats=["%Y-%m-%d", ]) start_time = forms.TimeField(input_formats=["%H:%M", ]) end_date = forms.DateField(input_formats=["%Y-%m-%d#", ]) end_time = forms.TimeField(input_formats=["%H:%M", ]) html form <form class="form-book" action="" method="POST" id="datetimepicker1"> {% csrf_token %} <label for="id_name">Name</label> <input type="text" name="name" maxlength="80" required_id="id_name" required> <label for="id_email">Email</label> <input type="email" required_id="id_email" name="email" max_length="254" required> <label for="id_start_date">Start Date</label> <input type="date" name="start_date" required_id="id_start_date" class="datepicker" required> <label for="id_start_time">Start Time</label> <input type="time" name="start_time" required_id="id_start_time" class="timepicker" required> <label for="id_end_date">End Date</label> <input type="date" name="end_date" required_id="id_end_date" class="datepicker" required> <label for="id_end_time">End Time</label> <input type="time" name="end_time" required_id="id_end_time" class="timepicker" required> <button class="btn btn-signup right" type="submit">Book</button> </form> -
Django/Bootstrap: form-check-inline not working
I want to display radio button inline using Boostrap. I've tryed to add bootstrap form-check-inline class by setting attrs attribute of Django widget. But When I debug, form-check-inline is not applyed. If I add form-check-inline class "manually" in div element containing radiobutton (see below) it works. template.html {{ form.eli_oui_ebo|as_crispy_field }} html page when inspected <div class=""> ***<= here should be applyed form-check-inline class**** <div class="form-check"> <label for="id_id_eli_oui_ebo_0_1" class="form-check-label"> <input type="radio" class="form-check-input" name="eli_oui_ebo" id="id_id_eli_oui_ebo_0_1" value="0" class="test"> Non </label> </div> <div class="form-check"> <label for="id_id_eli_oui_ebo_0_2" class="form-check-label"> <input type="radio" class="form-check-input" name="eli_oui_ebo" id="id_id_eli_oui_ebo_0_2" value="1" class="test"> Oui </label> </div> </div> form.py self.fields['eli_oui_ebo'] = forms.TypedChoiceField(label = 'A eu, dans les 72h, un contact avec un malade Ebola confirmé par RT-PCR',widget=forms.RadioSelect(attrs={'class': 'form-check-inline'},),required=False,choices=[i for i in Thesaurus.options_list(1,'fr') if i != (None,'')], empty_value=None, disabled=DISABLED)``` -
AttributeError: 'NoneType' object has no attribute 'group' trying to create a translation app for multiple language and I run into this error
this is my views.py def translate_app(request): if request.method == "POST": lang = request.POST.get("lang", None) txt = request.POST.get("txt", None) translator = Translator() tr = translator.translate(txt, dest="en") #huasa_tr = translator.translate(txt, dest= 'ha') #igbo_tr = translator.translate(txt, dest='ig') #yoruba_tr = translator.translate(txt, dest='yo') return render(request, 'translate.html', {"result": tr.text}) #result = {"result1":huasa_tr.text, "result2":igbo_tr.text, "result3":yoruba_tr.text}) return render(request, 'translate.html') -
TypeError : got multiple values for argument 'reports_pk'
I am currently running into the above error when trying to print some client details to a CSV file. I do understand what the error is stating, however, I don't see where the error occurs in my code. Please see the below code: Views.py function: def printViewCustomers(reports_pk): pkForm = get_object_or_404(SettingsClass, pk=reports_pk) complexName = pkForm.Complex connect = pyodbc.connect('DRIVER={SQL Server};' 'DATABASE=' + complexName + ';' ) viewCustomersSQL = ' Select Account , Name , Contact_Person , Telephone , Telephone2 , Fax1 , Fax2, EMail from dbo.Client Where DCLink <> 1 ' cursor = connect.cursor(); cursor.execute(viewCustomersSQL); viewCustomersData = cursor.fetchall() cursor.close() viewCustomers = [] for row in viewCustomersData: rdict = {} rdict["Account"] = row[0] rdict["Name"] = row[1] rdict["Contact_Person"] = row[2] rdict["Telephone"] = row[3] rdict["Telephone2"] = row[4] rdict["Fax1"] = row[5] rdict["Fax2"] = row[6] rdict["Email"] = row[7] viewCustomers.append(rdict) # Starting CSV response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=" ' + complexName + ' Customer Details.csv"' writer = csv.writer(response) writer.writerow([ 'Unit', 'Name', 'Contact Person', 'Telephone 1', 'Telephone 2', 'E-mail' ]) for x in viewCustomers: writer.writerow([ x["Account"], x["Name"], x["Contact_Person"], x["Telephone"], x["Telephone2"], x["Email"] ]) HTML refference to the function: {% extends "main/base.html"%} {% block content%} <h1 style=" text-align: center">Reports</h1> <hr> <br> {% for x in model %} <div class="row … -
drf error, 'Expected a dictionary, but got QuerySet.'
I have a problem with drf function view, I am getting an serializer error like this: {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got QuerySet.', code='invalid')]} Here's my function based view: @api_view(["GET","POST"]) def UserSearch(request): selected_users = Profile.objects.all() serializer = UserProfileSerializer(data=selected_users) if serializer.is_valid(): return Response(data=serializer.data) else: return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) My serializer: class UserProfileSerializer(serializers.ModelSerializer): class Meta: fields = ('user','name','surname','gender','country','city','sport') model = Profile And Profile model: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True) surname = models.CharField(max_length=50, blank=True) gender = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=50, blank=True) city = models.CharField(max_length=50, blank=True) sport = models.CharField(max_length=60, blank=True) #date_of_birth = models.DateField() def __str__(self): return f"{self.name} {self.surname} from {self.city}" -
How do I create a Django formset out of forms, each with a unique parameter?
In views.py: skill_list = [Skill.objects.get(tag_id=q.tag_id) for q in questions] skill_list = remove_duplicates(skill_list) skill_dict = [{'skill':skill} for skill in skill_list] SkillFormSet = formset_factory(SkillAnswerForm,extra=0) formset = SkillFormSet(initial=skill_dict) for form in formset: print(form.as_table()) In forms.py (please excuse the lack of path class indent): class SkillAnswerForm(forms.Form): def __init__(self,skill): super().__init__() questions = Question.objects.filter(tag_id=skill.tag_id) for question in questions: choices = question.ANSWER_CHOICES self.fields[question] = MultipleChoiceField(choices=choices) skill_id = CharField(max_length=1000) When formset is accessed (but no instantiated) the error TypeError: SkillAnswerForm.__init__() got an unexpected keyword argument 'auto_id' is returned. Thank you! -
How to access a http request.get.form variable into a python class?
I am developing flask app, Here is the app.py code: app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html') # uploading a csv file @app.route('/data', methods=['GET', 'POST']) def data(): if request.method == 'POST': file = request.files['upload-file'] global df df = pd.read_csv(file) columns = df.columns return render_template('data.html',columns=columns, data=df.to_html(max_rows=5, classes="table table-hover"), df=df) @app.route('/data/slamd', methods=['GET', 'POST']) def slamd(): print(data().df) # cannot recognize the df? fixedtargets = request.form.get('fixedtargets') features = request.form.get('features') targets = request.form.get('targets') s = sequential_learning(df) # this is a class return render_template('slamd.html', s=s, fixedtargets=fixedtargets, targets=targets, features=features) in my slamd.py, here is the code: from app import * class sequential_learning: def __init__(self,dataframe): self.dataframe=dataframe def apply_feature_selection_to_df(self,dataframe): features = sequential_process.features self.features_df = self.dataframe[features] Here in my slamd.py file, the variable features are not recognized? How to use these variables features, fixedfeatures and targets inside my class. Note: The df is also not working inside the sequential_process() function? and here is a sample of the view data.html: <div class="row"> <div class="col-sm-6"> <select multiple name="features" class="form-control"> <option value=""></option> {% for col in columns %} <option value="{{col}}">{{col}}</option> {% endfor %} </select> </div> -
module 'django.db.models' has no attribute 'model' Unresolved reference 'module'
I am creating A Realtime chat app using python,django,pycharm. there is following error occurs "Unresolved reference 'models'" -
Django: UNIQUE constraint failed: users_customuser.email
i keep getting this error when i try to register for the second time i have tried multiple possible solutions but i keep getting it anyway any help ? IntegrityError at /registration/transporteur this is my code: here i try to have multi type users models.py class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length= 15, ) first_name = models.CharField(max_length= 15) last_name = models.CharField(max_length= 15) email = models.EmailField(_('email address'),unique= True,) phone_number = models.CharField(max_length= 15) address = models.CharField(verbose_name = "Address", max_length= 50, null = True, blank= True) # profile_picture = models.ImageField(null = True) # longitude = models.CharField(verbose_name = "Longitude", max_length= 100, null = True, blank= True) # lagitude = models.CharField(verbose_name = "Lagitude", max_length= 100, null = True, blank= True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_transporteur = models.BooleanField(default= False) is_client = models.BooleanField(default= False) is_staff = models.BooleanField(default= False) is_superuser = models.BooleanField(default= False) is_active = models.BooleanField(default= False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name", "username", "phone_number", "address"] objects = CustomUserManager() def __str__(self): return self.username def has_perm(self, perm: str, obj: None): return self.is_admin def has_module_perms(self, app_label): return True class Trasporteur(CustomUser): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="trasporteur_account") matricule = models.CharField(max_length = 20, blank=True, null=True) car_type = models.CharField(max_length = 20, choices = CAR_tYPES) rating = models.IntegerField(blank=True, null = True) current_location = … -
Django Rest Framework - filters models where ArrayField includes value1 OR value2, not subset
straight to the point. This is my model: class Product(models.Model): brand = models.CharField(max_length=40) model = models.CharField(max_length=40) price = models.FloatField(default=0) colors = ArrayField(models.CharField(max_length=20), blank=True, null=True, default=[]) sizes = ArrayField(models.IntegerField(), blank=True, null=True) discount_price = models.FloatField(null=True, blank=True, default=list) date_added = models.DateTimeField(auto_now_add=True) desc = models.TextField(default=None, blank=True, null=True) gender = models.CharField(choices=GENDER_CHOICES, blank=True, null=True, max_length=10) for_kids = models.BooleanField(blank=True, null=True) Serializer: class ProductsSerializer(serializers.ModelSerializer): pictures = ProductPicturesSerializer(many=True, read_only=True) average_rating = serializers.SerializerMethodField() def get_average_rating(self, obj): return obj.average_rating class Meta: model = Product fields = ['id', 'brand', 'model', 'price', 'discount_price', 'date_added', 'for_kids', 'gender', 'average_rating', 'sizes', 'colors', 'pictures'] My custom filter: class CharArrayFilter(filters.BaseCSVFilter, filters.CharFilter): pass class ProductsFilter(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr='gte') max_price = filters.NumberFilter(field_name="price", lookup_expr='lte') colors = CharArrayFilter(lookup_expr='contains') class Meta: model = Product fields = { 'brand': ['in'], 'model': ['in', 'exact'], } The problem is, when Im filtering it with colors like: red,black,blue, it only displays objects which have subset of theese values in array, not one of them which is my goal. I cant find ANY lookup expression that would work,trying lookup_expr = colors__in also doesn't work if anyone is wondering. Like display all shoes which have value red OR black OR blue in this field. Please help, I've tried everything -
Need help in getting multiple IP devices data on web-server over local network (not on internet)
Consider we have multiple IP devices that are sending data continuously to the specific (server) IP over UDP, currently we have desktop application (as a server) to monitor/ handle devices, Now we want to shift this server application from desktop app to webserver! Please guide me is there any way to get UDP data on webserver backend and to be displayed to the webpage, There's also need to send specific command from server (webpage) to the specific device (as IP addresses of all devices are known) Please guide me if this is possible, I'm interested to work with Django, is it possible that I could receive/send UDP data from Django(python) backend over UDP and process to database and webpage? Please guide me if this is possible Note: Remember this is not internet while a local network where IPs of all devices are known -
how to install the newest version of Django
I want to install the latest version of Django What should I write using Pip? I wrote this code: pip install -
Django Rest Framework form JSON parse error
class MyAnimal(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='user') animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False) race = models.ForeignKey(AnimalBreed, on_delete=models.CASCADE, null=True) birthyear = models.CharField(max_length=16, null=True) color = models.ForeignKey(AnimalColor, on_delete=models.CASCADE, null=True) sex = models.ForeignKey(AnimalSex, on_delete=models.CASCADE, null=True) height = models.CharField(max_length=32, null=True) father = models.CharField(max_length=128, null=True) mother = models.CharField(max_length=128, null=True) doc_num = models.CharField(max_length=128, null=True, default='') entity = models.ForeignKey('entities.Entity', on_delete=models.CASCADE, null=True, blank=True) serializers.py from rest_framework import serializers from animals.models import MyAnimal class MyAnimalSerializer(serializers.ModelSerializer): class Meta: model = MyAnimal fields = ('id', 'user', 'name', 'animal', 'race', 'birthyear', 'color', 'sex', 'height', 'father', 'mother', 'doc_num',) views.py class MyAnimalFormApi(APIView): def post(self, request): serializer = MyAnimalSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) I cannot post this form through postman. When i put in body/raw(json) { "data": { "name": 'name', "animal" 'dog' } I get an error "detail": "JSON parse error - Expecting value: line 3 column 13 (char 26)" Yes i have an animal in my database named 'dog' -
Question on how to use graphene unions with django polymorphic
I have some polimorphic models class Product(PolymorphicModel): name = models.CharField(max_length=200) class Item(Product): pass class Service(Product): pass class Variant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variants") And I'm trying to implement django-graphene But I don't know how to properly do it class ItemType(DjangoObjectType): class Meta: model = Item fields = "__all__" class ServiceType(DjangoObjectType): class Meta: model = Service fields = "__all__" class ProductType(graphene.Union): class Meta: types = (ItemType, ServiceType) This is my Query: class Query(graphene.ObjectType): products = graphene.List(ProductType) items = graphene.List(ItemType) services = graphene.List(SeriveType) def resolve_products(self, info): return Product.objects.all() def resolve_items(self, info): return Item.objects.all() def resolve_services(self, info): return Service.objects.all() And i want to retrieve all products (instances of Items and Services) all at once, but I don't understand how to do it! { products { name } } returns: "Cannot query field 'name' on type 'ProductType'. Did you mean to use an inline fragment on 'ItemType' or 'ServiceType'?" how do I retrieve all objects at once? -
FileNotFoundError ,while Django - AWS S3 image file resizing
The Django website have media files on AWS S3, when Admin upload new image, model layer supposed to resize image and save. MODELS.PY class News(models.Model): photo=models.ImageField(upload_to='newsimage') def save(self, *args, **kwargs): img1 = Image.open(self.photo.name) if img1.height > 400 or img1.width > 400: output_size = (845,440) img1.thumbnail(output_size) img1.save(self.photo.name) def __str__(self): return self.title def get_absolute_url(self): return reverse('Newsdetail', kwargs={'slug': self.slug}) The code work fine when media stored in local storage. If the same in S3 , it makes error. However if I dont resize image and save directly , it works fine with AWS S3. -
What's the cleanest way of counting the iteration of a queryset loop?
I need to loop through a queryset and put the objects into a dictionary along with the sequence number, i, in which they appear in the queryset. However a Python for loop doesn't seem to provide a sequence number. Therefore I've had to create my own variable i and increment it with each loop. I've done something similar to this, is this the cleanest solution? ledgers = Ledger.objects.all() i = 0 for ledger in ledgers: print('Ledger no '+str(i)+' is '+ledger.name) i += 1 -
How to achieve database data persistence using factories in pyTest in Django?
I know that when we create a record in the test database inside 1st test case, it is not available from inside 2nd test case. If we use a fixture then the fixture will run before each test case and a new db record will be generated and provided to each test case. I have a factory defined as: import factory from faker import Faker fake = Faker() from django.contrib.auth.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = fake.name() which is used by a fixture, defined as: import pytest from django.contrib.auth.models import User from pytest_factoryboy import register from tests.factories import UserFactory register(UserFactory) @pytest.fixture def user_creation_through_fixture(db, user_factory): user = user_factory.create(username="persist") return user and 2 test cases defined as: import pytest def test1(user_creation_through_fixture): print(user_creation_through_fixture) assert True def test2(user_creation_through_fixture): print(user_creation_through_fixture) assert True how can i apply something like @pytest.fixture(scope="session") to the fixture ? so that at the time of 1st test case when fixture is run a new user record is created in db and then at the time of 2nd test case when fixture is run the same user record is provided to 2nd test case.