Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't update image in Django
I want to update image for ImageField but it won't update it's keep using default.jpg Here my models.py Here my form.py addproduct.html addproduct in views.py Thank you -
Memory Error while doing `request.POST.copy()'
I have a Django application that allows users to upload files. I do that using tastypie rest, it works perfectly with normal size files. but an error occurs when uploading a 500MB file. the error occurs at: multipart_data = request.POST.copy() The error is: Traceback (most recent call last): File "<env_path>\lib\site-packages\tastypie\resources.py", line 227, in wrapper response = callback(request, *args, **kwargs) File "<env_path>\lib\site-packages\tastypie\resources.py", line 467, in dispatch_list return self.dispatch('list', request, **kwargs) File "<env_path>\lib\site-packages\tastypie\resources.py", line 499, in dispatch response = method(request, **kwargs) File "<env_path>\lib\site-packages\tastypie\resources.py", line 1405, in post_list deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) File "<project_path>\apps\data_manager\rest.py", line 70, in deserialize multipart_data = request.POST.copy() File "<env_path>\lib\site-packages\django\core\handlers\wsgi.py", line 110, in _get_post self._load_post_and_files() File "<env_path>\lib\site-packages\django\http\request.py", line 315, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "<env_path>\lib\site-packages\django\http\request.py", line 275, in parse_file_upload return parser.parse() File "<env_path>\lib\site-packages\django\http\multipartparser.py", line 254, in parse chunk = handler.receive_data_chunk(chunk, counters[i]) File "<env_path>\lib\site-packages\django\core\files\uploadhandler.py", line 174, in receive_data_chunk self.file.write(raw_data) MemoryError -
Django get list of all models
I'm new in python and django. I have a file models.py in MyApp folder, It has about 20 model classes. I want to write a class that find all models in the MyApp and change the manager=True. from django.db import models class Model_One(models.Model): ... class Meta : managed = False class Model_Two(models.Model): ... class Meta : managed = False ... -
ufw forbids docker container to connect to postgres
On ubuntu 18.04 with ufw enabled I run docker container which is supposed to connect a django app to a locally installed Postgresql server. Everything runs perfect when ufw is disabled docker-compose -f docker-compose.prod.yml run --rm app sh -c 'python manage.py createsuperuser' But with enabled ufw I get the following error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Operation timed out Is the server running on host "host.docker.internal" (172.17.0.1) and accepting TCP/IP connections on port 5432? I have following ufw rules $ sudo ufw status Status: active To Action From -- ------ ---- Nginx Full ALLOW Anywhere OpenSSH ALLOW Anywhere 20/tcp ALLOW Anywhere 21/tcp ALLOW Anywhere 990/tcp ALLOW Anywhere 40000:50000/tcp ALLOW Anywhere Nginx Full (v6) ALLOW Anywhere (v6) OpenSSH (v6) ALLOW Anywhere (v6) 20/tcp (v6) ALLOW Anywhere (v6) 21/tcp (v6) ALLOW Anywhere (v6) 990/tcp (v6) ALLOW Anywhere (v6) 40000:50000/tcp (v6) ALLOW Anywhere (v6) -
How to automatically move my settings.toml to a settings.yaml when using dynaconf
I am using Dynaconf to manage configurations of my Django project. Dynaconf sucessfully generated a settings.toml file with the current development environment. I want to switch to using .yaml format that I read dynaconf supports. Is there an automatic way to translate the settings.toml to an settings.yaml using dynaconf cli? -
Pass a list to geodjango multipolygon lookup
I have a list of points like following: points_list = ['SRID=4326;POINT (-86.81013299999999 33.524658)', 'SRID=4326;POINT (-86.81255400000001 33.524854)'] Now I want to use this list to filter on a MultipolygonField. I can't pass this whole list to the multipolygon lookup because I get an error, Tuple too long for lookup covers. Now what I have done is simply loop through the list and save the filtered multipolygon objects in a new list like: Say geom below is a multipolygon field multipolygon_list = [] for point in points_list: dam_obj = DAM.objects.filter(geom__contains=point).values_list('id', flat=True) multipolygon_list.append(dam_object) Now what I want is to remove the loop above and all this is a single query. Is there a way to remove it? Like can't I do something like below? DAM.objects.filter(geom__contains=points_list)... -
trade off of different ways to access postgresql data within django
I am unclear about something. I have a script where I do a lot of data wrangling from django models using pandas. So far, I am importing data from postgresql in the following fashion and neither leveraging django framework for the calculation, kind of as such: conn = engine.connect() print("engine connected") metadata = sqlalchemy.MetaData() print("metadata acquired") parameters = sqlalchemy.Table('dashboard2_parameters2', metadata, autoload=True, autoload_with=engine) print("histo data loaded") query = sqlalchemy.select([parameters]) print("query done") resultproxy = conn.execute(query) print("resultproxy done") conn.close() result_set = resultproxy.fetchall() dt = pd.DataFrame(result_set) dt.columns = result_set[0].keys() print("parameters", dt) I am wondering if using: dt = parameters2.objects.all() would do the same thing? I am concerned also about speed as some of the table can get pretty big, what would be the trade off in terms of speed of the two techniques? -
Django ManyToMany field on custom column in existing database
I have a database with one table for recipes without the ingredients and one table with the ingredients each with a recipe id to reference each other. Now I don't know how to refer to the recipe id column, because at the moment (I build a rest API) it returns no ingredients. My models.py class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True, related_name='+') amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' class Recipe(models.Model): recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase. title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase. preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase. images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase. ingredients = models.ManyToManyField(Ingredients) class Meta: managed = True db_table = 'Recipes' I hope you understand my problem and can help me. Thank you very much! -
Django send_mail error using smtp.domain.com (smtplib.SMTPHeloError: (501, b'Syntactically invalid HELO argument(s)'))
I have a problem when sending an email using Django as the email I'm trying to send from is hosted on domain.com, I've tried to send from Gmail and it worked fine but when I use the configuration of domain.com it gives me this error: smtplib.SMTPHeloError: (501, b'Syntactically invalid HELO argument(s)') what I understand is that it is related to the host name, but I don't know what to do to fix that error and can I use a different hostname for domain.com that works. below is the configuration in setting.py and send_mail function: setting.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.domain.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'ARomayh@endorsefinance.com' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST_PASSWORD = "********" send_mail function: send_mail( 'HR Request', 'your request is being processed', 'ARomayh@endorsefinance.com', ['ARomayh@endorsefinance.com'], fail_silently=False, ) return HttpResponse('Mail sent') -
images_data = validated_data.pop('images') KeyError: 'images'
I am trying to upload multiple images to the article as ArrayField(ImageField()) is not working on Django right now. Here are my codes: Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') class ArticleImages(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to='images',null=True,blank=True,) article = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True,related_name='images') Serializers.py class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True,allow_null=True) class Meta: model = Article fields = ('id','author','images') def create(self, validated_data): images_data = validated_data.pop('images') article = Article.objects.create(**validated_data) for image_data in images_data: ArticleImages.objects.create(article=article, **track_data) return article Views.py class ArticleView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleViewSerializer permission_classes = (AllowAny,) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleViewSerializer(data=request.data) if serializer.is_valid(): article = serializer.save() serializer = ArticleViewSerializer(article,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ArticleImagesView(CreateAPIView): queryset = ArticleImages.objects.all() serializer_class = ArticleImagesViewSerializer permission_classes = (AllowAny,) def get(self, request, format=None): queryset = ArticleImages.objects.all() serializer = ArticleImagesViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleImagesViewSerializer(data=request.data) if serializer.is_valid(): articleimages = serializer.save() serializer = ArticleImagesViewSerializer(articleimages,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now i am facing with an issue that gives KeyError: images_data = validated_data.pop('images') KeyError: 'images' … -
hot to write create function for this view in one post form, i want to create with template
enter image description hereand second question: how i post this form from my template (html file) i have two forign key in one model, i cant write create post form as django default admin models.py class Survey(models.Model): GENDER = ( ('male', 'male'), ('female', 'female'), ) full_name = models.CharField(max_length=255) gender = models.CharField(choices=GENDER, max_length=50) room = models.IntegerField() phone = models.CharField(max_length=15) feedback = models.TextField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}'.format(self.full_name) class Service(models.Model): service = models.TextField() average = models.FloatField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}'.format(self.service) class ServiceEvaluation(models.Model): RANK = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), ) survey = models.ForeignKey(Survey, on_delete=models.SET_NULL, null=True) service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name='ranks') rank = models.PositiveIntegerField(choices=RANK, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) -
Django: Form default date different on production server
I have a AddRecordTimeFrame form. class AddRecordTimeFrame(forms.ModelForm, OverviewAddTimeframeMixin): start_date = forms.ChoiceField(label='Start Date:',widget=forms.Select(attrs={'style': 'width:140px'}),choices=get_datetime_choices('date'),initial=datetime.date.today()) start_time = TimeFieldHHSS(widget=forms.TimeInput(attrs={'style': 'width:80px;height:23px'})) class Meta: model = RecordModel fields = ('test_cell','start_date','start_time',) labels = RecordModel.RECORD_NAMING_CONV The initial value being datetime.date.today(), returns correctly on my Development server but does not on Production server. But in fact returns the date in which I last restart the server as the initial value (Which was Oct 13 2020). Development Version Production Version I would like to determine the cause of this behavior and how to rectify the issue to allow the current datetime to show as default in the production server. Software Both use same version of source code and requirements versions(Python, Django etc.) Both MariaDB Development Windows 7 Production Linux (Debian) NginX Gunicorn -
Create localized django app and use the localization from other app
I have the following problem: I created a Django app (app1) and then installed it in other one (app2). Now I'm trying to make the internationalization of the site, but I want to be able to use the installed app translations and I cannot even compile them. Some useful information: APP 1 . ├── MANIFEST.in ├── app1 │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── locale/ │ │ ├── en-us │ │ │ └── LC_MESSAGES │ │ │ └── django.po │ │ ├── es │ │ │ └── LC_MESSAGES │ │ │ └── django.po │ │ └── pr │ │ └── LC_MESSAGES │ │ └── django.po │ ├── migrations/ │ ├── models.py │ ├── settings.py │ ├── static/ │ ├── templates │ ├── tests.py │ ├── urls.py │ ├── utils.py │ └── views.py └── setup.py APP 2 (the one that has APP 1 installed) ├── app2/ │ ├── locale/ │ │ ├── en-us/ │ │ │ └── LC_MESSAGES │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── es/ │ │ │ └── LC_MESSAGES │ │ │ ├── django.mo │ │ │ └── django.po │ │ └── pr/ │ │ └── … -
Group by time period - Django
class Book(models.Model): BOOK_CATEGORY = (('0', 'Romance'), ('1', 'Novel'), ('2', 'Comedy')) price = models.FloatField() category = models.IntegerField(choices=BOOK_CATEGORY) publishing_year = models.DateField() What would be the best way query wise to get the average price of the books with a dynamic period? So average of books sold monthly , quarterly , half year etc. -
Mongoengine referencefield
Here's an example code: class A: pass class B: a = mongoengine.fields.ReferenceField(A, verbose_name='a') What would be the best practice to query A.b. Of course I can make a @property b with complicated query, but I thought maybe there is something out of the box specially for that, unfortunately I couldn't find anything. -
Why is my TypeError saying 'unsupported operand type(s) for +: 'int' and 'str'
I'm running Django and trying to do an e-commerce site. I'm working with totals in my cart to get the following: Total number of cart items Retrieve all cart items Total cost of all items. my code is as follows models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total line 54 in models.py is total = sum([item.get_total for item in orderitems]) views.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: # Create empty cart for now for non-logged in user items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} context = {'items': items, 'order': order} return render(request, 'IT6041App/cart.html', context) cart.html {% extends "IT6041App/base.html" %} {% load static %} {% block content %} <br><br><br> <div class="row justify-content-md-center"> <div class="col-lg-6"> <br> <div class="box-element"> <div class="cart-row"> <a class="btn btn-outline-dark" href="{% url 'index' %}">Continue Shopping</a> <div style="flex:1"></div> <div style="flex:1" align="center"><strong>Item</strong></div> <div style="flex:1" align="center"><strong>Price</strong></div> <div style="flex:1" align="center"><strong>Quantity</strong></div> <div style="flex:1" align="center"><strong>Total</strong></div> </div> {% for … -
Failed lookup for key [user] in <User: test> error when testing a view
I have a freind requests app that can send/cancel/accept/delete friend requests and I am trying to test it, however when I'm accepting a friend request and adding users to each other friend lists I am getting a Failed lookup for key [user] in <User: test> exception. models.py class User(AbstractBaseUser, PermissionsMixin): name = models.CharField('Full Name', max_length=35, unique=True, null=False, blank=False) friends = models.ManyToManyField("User", blank=True) def __str__(self): return self.name class FriendRequest(models.Model): objects: models.Manager() to_user = models.ForeignKey(User, related_name='to_user', on_delete=models.CASCADE) from_user = models.ForeignKey(User, related_name='from_user', on_delete=models.CASCADE) views.py from django.db import transaction def accept_friend_request(request, pk): try: with transaction.atomic(): from_user = User.objects.get(pk=pk) f_request = FriendRequest.objects.filter( from_user=from_user, to_user=request.user ).first() user1 = f_request.to_user user2 = from_user user1.friends.add(user2) print(user1.friends.all()) user2.friends.add(user1) print(user2.friends.all()) f_request.delete() return redirect(request.get_full_path()) except Exception as ex: print(ex) return HttpResponse('User does not exist') Here as you can see I am using the transaction.atomic() to prevent the exception from breaking the unittest transaction. tests.py def setUp(self): self.client = Client() self.user = User.objects.create_user(email='test@gmail.com', name='test', password='test') self.user1 = User.objects.create_user(email='test1@gmail.com', name='test1', password='test1') self.client.force_login(self.user) def test_accept_friend_request(self): friend_request = FriendRequest.objects.create(from_user=self.user1, to_user=self.user) self.client.get(reverse('accept_friend_request', kwargs={'pk': self.user1.pk}), follow=True) self.assertIn(self.user, self.user1.friends.all()) self.assertIn(self.user1, self.user.friends.all()) In my test I create a friend request object and send an accept request to the view which should add each of the users to each one … -
Django formtools user registrations password
Trying to create user using django-formtools. forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = User fields = ('username', 'password1', 'password2') class CustomProfileCreateForm(forms.ModelForm): class Meta: model = User fields = ('name', 'email') views.py class SignupWizard(SessionWizardView): template_name = "user/registration.html" form_list = [CustomUserCreationForm, CustomProfileCreateForm] instance = None def get_form_instance(self, step): if self.instance is None: self.instance = User() return self.instance def done(self, form_list, **kwargs): self.instance.save() return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) All are ok except password. Password is not set. How to save form correctly -
Difference in time between database and value displayed
I am trying to fix strange problem with time in my project. First of all my settings are as follows: settings.py LANGUAGE_CODE = 'pl-pl' TIME_ZONE = 'Europe/Warsaw' USE_I18N = True USE_L10N = False USE_TZ = True DATETIME_FORMAT = 'Y-m-d H:i:s' DATE_FORMAT = 'Y-m-d' Every DateTimeField field, for example: models.py class Order(models.Model): date_zal = models.DateTimeField() is displayed correctly in my home.html file with the help of {{ order.data_zal }} but when I look into my database (still Sqlite3, going to switch to MySql soon) there is ALWAYS date with 1 hour earlier (e.g. 11:40 displayed vs 10:40 in database). Not sure where lies the problem since it is displayed properly. -
Django RestApi Problem : viewsets in views not found
I tried to create an api for my project, but somehow I cant retrieve the viewsets on my function, what did I do wrong? -
Make thumbnail from jpg, jpeg or png
I have the following method to create a thumbnail, but I would like it also to generate it in case the file type is png, as it currently throws an error for them: from io import BytesIO from django.core.files import File from PIL import Image def make_thumbnail(image, size=(600, 600)): im = Image.open(image) im.convert('RGB') im.thumbnail(size) thumb_io = BytesIO() im.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail How can I effectively accept png, jpg and jpeg to generate the thumbnail? -
drf_yasg - swagger request url issue
I have a project with Django + Nginx + Gunicorn setup. In this project, I am running Nginx with 8000 port, here when I test endpoints using postman it is working fine but when I use Swagger it is not working. Swagger was trying to access the URL without the port ( ex: curl -X GET "http://172.16.235.109/runs/" -H "accept: application/json" ). so it is not working. I explored a lot but I could not find the right way to solve this problem. Anyone, could you please help me to resolve this issue? Requirements am using Django==3.0.3 drf-yasg==1.17.1 (SWAGGER) gunicorn==20.0.4 -
QueryDict Object has no attribute session Django
So I basically have a login form which I have defined like this: def login_request(request): if request.method == 'POST': data = request.POST auth_backend = AuthenticationBackend() login_form = LoginForm(data) if login_form.is_valid(): user = auth_backend.authenticate(data, password=data['password'], email=data['email']) if user: login(data, user) # redirect to homepage else: login_form.add_error('password', "Password doesn't match email") else: data = {} login_form = LoginForm() return render(request, 'login.html', {'form': login_form, 'data': data}) If the given conditions match, the user must be logged in. However, when I do login(data, user) I get this error: Internal Server Error: /users/login/ Traceback (most recent call last): File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\users\views.py", line 34, in login_request login(data, user) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\contrib\auth\__init__.py", line 99, in login if SESSION_KEY in request.session: AttributeError: 'QueryDict' object has no attribute 'session' Why is this happening? How can I fix this? Please help me, thanks in advance! -
too late for learning flask? and how shloud I shoose my DB?
I'm a junior web developer and I completed all of what I need from front end develpoment and a little more: html/css/js vue python c# ps: dropped this one and now I'm starting with backend development, so I started with django and found out that it's a little too complicated but I continued for a while and now I hear people saying that if you want to start with a web framework you should start with flask even if your end goal is django. So that got me thinking that I'm still finding django a bit hard and slow to learn for me and I thought that am I doing it wrong and that I should stop learning django and just start slow. keep in mind I don't know that much of django to say I'm too late or early and I should switch. so what do you think I should do at this point? and additionally I searched about answers to what sql should I learn and got lost in the answers. sql sounds nice, sqlite comes with django and flexible, mongodb is too easy and postgresql also seems like a good choice so I don't know where to … -
index page not displaying and returning error 200 on Django terminal
i have an index page which extends a navbar.html in Django and is followed by other codes. when i run the server, the server runs but displays "GET /health/ HTTP/1.1" 200 4619" which i understand is a blank page but my index.html is not blank. The page shows the extended navbar.html but nothing more. The views look like: def index(request): return render(request, 'My_Doc/index.html') And urls look like: urlpatterns = [ path('', views.index, name='index'), ] Requesting for help>>>>