Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to backup postgis database via terminal in linux?
I tried to back up a PostGIS database via terminal from the info from the site https://postgis.net/workshops/postgis-intro/backup.html like this pg_dump --file=test_pro.backup --format=c --port=5432 --username=postgres test_pro but I am encountering an error like this pg_dump: [archiver (db)] query failed: ERROR: could not access file "$libdir/postgis-2.5": No such file or directory pg_dump: [archiver (db)] query was: SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, a.attnotnull, a.atthasdef, a.attisdropped, a.attlen, a.attalign, a.attislocal, pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, array_to_string(a.attoptions, ', ') AS attoptions, CASE WHEN a.attcollation <> t.typcollation THEN a.attcollation ELSE 0 END AS attcollation, a.attidentity, pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(option_name) || ' ' || pg_catalog.quote_literal(option_value) FROM pg_catalog.pg_options_to_table(attfdwoptions) ORDER BY option_name), E', ') AS attfdwoptions FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t ON a.atttypid = t.oid WHERE a.attrelid = '23466'::pg_catalog.oid AND a.attnum > 0::pg_catalog.int2 ORDER BY a.attnum this is my django database setting DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'test_pro', 'USER': 'postgres', 'PASSWORD': 'test_pro', 'HOST': 'localhost', 'PORT': '5432', } } what can I do to backup the PostGIS database via the terminal in linux -
django admin site has been occurred with s3, cloudfront
enter image description here enter image description here As you can see above, I'm using AWS S3 and Cloudfront through the django-storages library. But since I recently started using the cloudfront key, 403 errors have occurred on the admin site. -
Django error updating -> invalid literal for int() with base 10
i have the following problem when i tried to update a Ingredient... Internal Server Error: /menu/edit-plate/a6bf6537-878e-4321-8446-f3caad5a71dc Traceback (most recent call last): File "/home/l30n4rd0/.local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'a6bf6537-878e-4321-8446-f3caad5a71dc' ¿Can you help me? Here my code: Model: from django.db import models from django.urls import reverse import uuid from menu.models.ingredient import Ingredient class Plate(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID único para este plato") title = models.CharField(max_length=200) ingredient = models.ManyToManyField(Ingredient, help_text="Seleccione un ingrediente para este plato") def __str__(self): """ String que representa al objeto Book """ return self.title def get_absolute_url(self): """ Devuelve el URL a una instancia particular de Menu """ return reverse('plate-details', args=[str(self.id)]) def get_edit_url(self): """ Devuelve el URL a una instancia particular de Menu """ return reverse('edit-plate', args=[str(self.id)]) View functions: class PlateCreate(generic.CreateView): model = Plate fields = ['title', 'ingredient'] success_url = 'plate-list' class PlateDetailView(generic.DetailView): model = Plate class PlateUpdate(generic.UpdateView): model = Ingredient fields = ['title', 'ingredient'] template_name_suffix = '_update_form' success_url = '/menu/plate-list' class PlateListView(generic.ListView): model = Plate Template: <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Update"> </form> Urls.py from django.conf.urls import url from django.urls import path, include from . import views urlpatterns = [ url(r'^create-plate$', views.PlateCreate.as_view(), name='create-plate'), url(r'^plate-list/$', … -
How to fix Facebook has detected MyAppName isn't using a secure connection to transfer information
I am trying to implement facebook social Oauth login on my Django app but I am faced with the below error. I have tried changing my http protocol from http to https on Valid OAuth Redirect URIs. But I am still faced with the same problem. -
Deploy Django app on Microsoft Azure with Local Package
I would like to deploy an Django App on to Microsoft Azure through the App Service. In the requirements.txt I have a package that I wrote myself and need to install from local directory which is in the same directory as manage.py. I have tried to deploy the app through local git, and everytime it is running into the error it is not able to import the local package although it is able to install it with no problem in "antenv" (the virtual env Azure creates automatically) -
'decimal.Decimal' object is not iterable an error occurred django
im getting an error while trying to loop and get total of a decimal object in a django model, tried so many soloutions all failed. thr error is 'decimal.Decimal' object is not iterable and here is the model and object.. class Order(models.Model): # customer = models.ForeignKey(Customer, on_delete=models.CASCADE) total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) #success = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now=True) # product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return 'Order {0}'.format(self.id) @property def order_prices(self): order = 0 for o in self.total_price: order += o return order -
How can I get unread messages for each user?
I'm creating a django web application. I want to create a one way messaging system so users can receive messages from admin. Currently I did this using a model like below: from django.db import models from django.contrib.auth.models import User class AdminMessage(models.Model): title = models.CharField(max_length=120) receivers = models.ManyToManyField(User) message = models.TextField() is_read = models.BooleanField(default=False) the problem is I want each user to be able to see his unread messages in his profile. how can I do that? -
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