Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django app with PointField, gis_model and postgris database
I'm trying to deploy my first wab app, and I need to use Postgris databas and tacking geolocation for some models. I found it very hard to set this deployement, I get some errors and can't figure out how to solve the error, my question is there is a tutorial that I can see to learn how to deploy sache application, all tutorial I found don't see haw to set up heroku for such case. -
Django view triggered twice after submit button
I found out that I returned the context to my HTML template the view called in the first time, after I hit the submit button the view triggered again from the beginning. how I can prevent the view to triggered from the beginning and execute directly the code after is request.method == 'POST'. this is the code of my view def recipe_recommendations(request): print('enter----------------') # add rating of current user to rating matrix person = request.session['person_id'] user_category = FoodCategory.objects.filter( person_id=request.session['person_id']).values_list('category', flat=True) user_category = user_category[0] target_user = add_to_csv(person, category=user_category) # get recommendation recom_size = 5 htop_n_for_target_user = [] unhtop_n_for_target_user = [] htop_n_for_target_user,unhtop_n_for_target_user = get_top_n_for_user(person,recom_size, user_category) # get recipe info and send them to tmeplate id_h_recipes = [] # for i in htop_n_for_target_user: # id_h_recipes.append(i[0]) [id_h_recipes.append(i[0]) for i in htop_n_for_target_user] id_unh_recipes = [] [id_unh_recipes.append(i[0]) for i in unhtop_n_for_target_user] # for i in unhtop_n_for_target_user: # id_unh_recipes.append(i[0]) print(f'-------healthy_ids: {id_h_recipes}') print(f'--------unhealthy_ids: {id_unh_recipes}') # extract 5 healthy recipes h_0_recipe = HealthyRecipe.objects.get(id=id_h_recipes[0]) h_1_recipe = HealthyRecipe.objects.get(id=id_h_recipes[1]) h_2_recipe = HealthyRecipe.objects.get(id=id_h_recipes[2]) h_3_recipe = HealthyRecipe.objects.get(id=id_h_recipes[3]) h_4_recipe = HealthyRecipe.objects.get(id=id_h_recipes[4]) # extract 5 unhealthy recipes unh_0_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[0]) unh_1_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[1]) unh_2_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[2]) unh_3_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[3]) unh_4_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[4]) # selected recipe model selected_recipe = SelectedRecipe() if request.method == "POST": # if the … -
Python geojson get centroids of polygon
I have a django model from django-leaflet example project like: from djgeojson.fields import PolygonField from django.db import models class MushroomSpot(models.Model): title = models.CharField(max_length=256) description = models.TextField() geom = PolygonField() After saving a data I get result like: 'title': 'Location 2', 'description': 'This is location 2', 'geom': {'type': 'Polygon', 'coordinates': [[[5.328369, 45.251688], [5.910645, 44.980342], [6.328125, 45.375302], [6.075439, 45.859412], [5.471191, 45.698507], [5.328369, 45.251688]]]} Here how can I get cetroid and area of the polygon ? I tried searching but found very complicated. Any help will be appriciated -
Uploading image/images on Django REST Framework
I am trying to upload images on an endpoint in postman but i'm getting the error in the screenshot below Below is my code for sake of brevity i'll only send the affected parts. Models: class Post(models.Model): content = models.TextField() image = models.ManyToManyField(PostImage,blank=True,related_name='posts_images') class PostImage(models.Model): image = models.ImageField(upload_to='post-images',validators=[FileExtensionValidator(['png','jpg','gif','jpeg'])]) Serializers: class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('image') class PostSerializer(serializers.ModelSerializer): image = PostImageSerializer(many=True, required=False) class Meta: model = Post fields = ['content','image',] def create(self, validated_data): r_data = self.context['request'].FILES instance = super().create(validated_data) if "image" in validated_data.keys(): images = validated_data.pop('image') else: pass post = Post.objects.create(**validated_data) instance.image.add(r_data) return post Viewsets : class PostViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() -
Render response in django python
Using django framework and rest api framework. os.environ['NO_PROXY'] = '#mylocalhosthere' def api_view(request): #url = '#mylocalhosthere/pcp/customer/' url = '#mylocalhostherepcp/customer/?format=json' r = requests.get(url) data = json.loads(r.text) return render(request,'PcPeripherals/api.html',{'response':data}) This is what my django template looks like: {% block content %} <div class="row"> <div class="column-d-9 column-t-12 column-m-12"> <div id="box_contact"> <div id="box_formas"> <h1>List of customers</h1> {% for i in data%} <strong>{{i.id}}</strong> {% endfor %} </div> </div> </div> </div> {% endblock content %} Any ideas what I am doing wrong? I checked some other variants still no data in my template. -
why does Django not allow users to login?
I'm struggling with login in both the "normal" part of the site and in the standard admin page. I tried to delete the old db and create a brand new one with a new superuser, but I didn't solve the problem. I can submut the form and the server response is 302 and it redirects again in the login page. Can someone help me out? I'm going crazy. All other solution here does not work and even from other sites. I'm on Django 3.1.6 Thanks a lot -
Django Custom User Manager is not called in admin panel
I am implementing a custom user model using AbstractBaseUser and BaseUserManaer . class UserManager(BaseUserManager): def create_user(self,username,password=None): class User(AbstractBaseUser): ... objects = UserManager() When I am creating new users from the the terminal, it is working as intended and the users are getting registered using the custom UserManager. But when using the admin site, the user seems to be using some other user manager, where it should be using the custom user manager. users/admin.py User = get_user_model() class UserAdmin(BaseUserAdmin): ... admin.site.register(User, UserAdmin) -
Get next/previous sibling in Django CMS
I want to make previous/next buttons, which takes user to previous/next sibling, from the template inside Django CMS. I've tried this solution, but it doesn't work. How can I do that? -
Can't I add a list to my models.py in django?
I'm quite new in Django and in this project I need to manage information about a restaurant. The problem is that I can't add more than one ingredient required to a recipe My models.py is this: from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=35) quantity = models.IntegerField() unit = models.CharField(max_length=5) unit_price = models.FloatField() def __str__(self): return self.name class MenuItem(models.Model): title = models.CharField(max_length=35) price = models.FloatField() example = models.ImageField() def __str__(self): return self.title class RecipeRequirement(models.Model): menu_items = models.ForeignKey(MenuItem, default = 1, on_delete=models.SET_DEFAULT) ingredient = models.CharField(max_length=35) quantity = models.FloatField() def __str__(self): return str(self.menu_items) class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, default=1, on_delete=models.SET_DEFAULT) timestamp = models.DateTimeField() def __str__(self): return 'Purchase ' + str(self.menu_item) + str(self.timestamp) -
Django: Combine two count annotations from two filter queries
I am computing some statistics based on two different filters, but I'm not sure how I can combine both results into a single QuerySet. My code looks like this: qs1 = User.objects.filter(c1).annotate(count1=Count("id")) qs2 = User.objects.filter(c2).annotate(count2=Count("id")) I would like to create a third queryset, qs3 which has both count1 and count2. Basically I want to left join on User.id but I can't find a straightforward way of doing that. -
Django: capture authorization token from another service
I'm trying to capture an authentication token from another service authenticator. In summary, I have a form login that serve client with two options to sign in, throw the normal login, or a link to a second authenticator service which will redirect to a particular form page. Once the user is signed, this second authenticator service will redirect back to my application, with a token as param. I would like to include a kind of listener in my application (small script), in a way that when this redirect happen, I could capture and validate the token, finally, authenticate the user in the local django application. -
Django Rest Framework Viewsets Count Foreign Key
I am trying to add a additional field to my modelviewset. For example, if I have 1 parent and 3 children objects, I would like parent viewset json to look like. To get the count of the children I can do something like children = Child.objects.filter(parent.id=).count(), but I'm not sure how to get the parent id inside the view set. [ { "id": 1, "name": "parent1", "child_count": 3 } ] models.py class Parent(models.Model): name = models.CharField(max_length=100) class Child(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey("Parent", on_delete=models.CASCADE) views.py class ParentViewSet(viewsets.ModelViewSet): serializer_class = ParentSerializer children = Child.objects.filter() # ?? def get_queryset(self): queryset = Parent.objects.all().annotate(child_count=) # ?? return queryset serializers.py class ParentSerializer(serializers.ModelSerializer): child_count = serializers.IntegerField() class Meta: model = Parent fields = ["id", "name", "child_count"] -
How to make django boolean field true using a method in django models
I working on an e-commerce website I have the field about new arrivals so any product which is created in the last 30 days should be listed as a new arrival. In my models, I have a boolean field as is_new and the default value is false and I made a method to check the date whether the product is included in the new arrival list or not. but in my method new_arrival when I return self.is_new I get an invalid syntax. class Product(models.Model): name = models.CharField(max_length=200) description = models.TextField() price = models.IntegerField() picture = models.ImageField(upload_to='picture/') is_popular = models.BooleanField() is_cart = models.BooleanField() is_arrival = models.BooleanField(default=False) created_date = models.DateTimeField(aut_now_add=True) def new_arrival(self): if self.created_date >= self.created_date - self.created_date.timedelta(days=30): return self.is_new=True else: return self.is_new = False -
how to update value the field in model django of an object that belongs to a class that inherits from another abstract class?
class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class PublicModel(models.Model): public_id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True) class Meta: abstract = True class People(BaseModel): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Address(BaseModel): postal_code = models.CharField(max_length=255, null=True) public_place = models.CharField(max_length=255, null=True) class Contact(BaseModel): email = models.EmailField() phone = models.CharField(max_length=255, null=True) class Member(BaseModel, PublicModel): name = models.CharField(max_length=255) person = models.OneToOneField(People, on_delete=models.PROTECT) class Meta: abstract = True class Hub(BaseModel): description = models.CharField(max_length=255) address = models.ForeignKey(Address, on_delete=models.PROTECT) contact = models.OneToOneField(Contact, on_delete=models.PROTECT) class Partner(Member): hub = models.ForeignKey(Hub, on_delete=models.PROTECT, null=True) When updating a People or Hub object I would like the updated_at the Partner field also updated to reflect the current time of this modification. As it is, when updating a People or Hub object only its field updated_at has the updated time. What is the best approach to doing this? At the moment I am updating in a way that I think is very bad. Forcing Partner object update by passing a value to public_id so that updated_at has its updated value. Partner.objects.update_or_create(id=partner.id, defaults={'public_id': kwargs['public_id']}) -
how to extend class bassed view
I've crated class-based-view which shows content of the post.I also added the ability to make comments there, however the comment form dosn't work. views.py class PostDetailView(DetailView): model=Post template_name='blogdetail.html' pk_url_kwarg='id' def comments(request): comments=post.comments.all() new_comment=None if request.method=="POST": comment_form=CommentForm(data=request.POST) if comment_form.is_valid(): new_comment=comment_form.save(committ=False) new_comment.post=post new_comment.save() else: comment_form=CommentForm() return render(request, 'allblogs.html', {'comments':comments, 'comment_form':comment_form, 'new_comment':new_comment}) forms.py class CommentForm(forms.ModelForm): class Meta: model=Comment fields=['post','body'] blogdetail.html {% extends 'base.html' %} {% block content %} <h1>{{post.title}}</h1> <p>{{post.created_on}}</p> <p><a href="{% url 'userpage' post.author.username %}"></a>:{{post.author}}</p> <p>{{post.text}}</p> <form> {{comment_form.as_p}} <p><input type="submit" value="add"></p> {% csrf_token %} </form> {% endblock content %} -
How can we calculate average difference of datetime fields from related table in django?
I have two models Gigs and Orders. and want to calculate the average of diffrence between order_start_time and order_completed_time of every gig. check my code its giving following error Cannot resolve keyword 'orders' into field. Choices are: category, category_id, details, gig, id, images, price, reviews, seller, seller_id, title please help! Models.py (in seller app) class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if self._average_completionTime is not None: return self._average_completionTime return self.gig.aggregate(Avg('order_completed_time'-'order_start_time')) I think here the problem is in average completion time how can I use 'order_completed_time'-'order_start_time' in one variable that I should refer in views.py Models.py(in buyer app) focus on item field from seller.models import Gigs class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') order_start_time = models.DateTimeField(default=None) order_completed_time = models.DateTimeField(default=None) created_at = models.DateTimeField(auto_now_add=True) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.all().annotate(_average_rating=Avg('orders__time')) serializer_class = GigsSerializerWithAvgTime permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) Serializers.py class GigsSerializerWithAvgTime(serializers.ModelSerializer): average_completionTime = serializers.SerializerMethodField() def get_average_completionTime(self, … -
In Django, how can i get the specific method of a class based view that is being called with a request?
I'm working on a middleware that needs to execute some routine based on if the method that is being called in a class based view has a decorator. I tried using resolve(url), but this only returns the class. Is there a way to get the specific method of a class based view based on a request? -
Django ModelForm: changing the format of a dropdown list with initial value
I created a form in Django with ModelForm: class FormulariMostra(ModelForm): class Meta: model = Sample fields = ("name", "sample_id_sex", "pools",) pools is a foreign key (m2m relationship). In my views.py I added an initial value for the field pools: formulari_mostra=FormulariMostra(initial={'pools':1}) In the form the options for the field pools are ordered by id in descending order. My problem is that the dropdown list appears like this: With the initial (default) value highlighted and what I want is that the value with the id with the highest number appears the first one: Is there a way to do this maintaining the initial value? Or to hide this specific value? -
Deploying Django application with Heroku and getting AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
I'm triying to deploy my app to Heroku, Iget this error: AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' my DATABASE setting in the settings.py: import dj_database_url ... if DEVELOPMENT_MODE is True: DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": "manage", "USER": "testuser", "PASSWORD": "Lin123", "HOST": "localhost", "PORT": "", } } elif len(sys.argv) > 0: if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.config(), } ... import django_heroku GEOS_LIBRARY_PATH = os.getenv("GEOS_LIBRARY_PATH") GDAL_LIBRARY_PATH = os.getenv("GDAL_LIBRARY_PATH") django_heroku.settings(locals()) It's my first deploy of an app and I'm not sur about what I'm doing wrong -
Better way to fetch related object, in Self Refrencing ManyToMany Relationship?
I am working on a small application containing models CustomUser and PollQuestion. CustomUser having ManyToMany relation between itself and a CustomUser can have multiple PollsQuestion as well so there is Foreign Key relation between them. An authenticated user is only able to see polls raised by users he is following, to full-fill this requirement i have written following view**:-** def all_polls_utils(request): following = request.user.get_all_followings().values_list("id") user_id = [id[0] for id in following] all_polls = PollQuestion.objects.none() for u_id in user_id: user = CustomUser.objects.get(id=u_id) polls = user.poll_questions.all() all_polls = all_polls | polls return all_polls Main Question:- Is there in better way to do the same? Any suggestion will be highly appretiated I am posting the models bellow:- from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): email = models.EmailField(max_length=250, null=False) name = models.CharField(max_length=50, null=False) username = models.CharField(max_length=50, null=False, unique=True) password = models.CharField(max_length=15, null=False) user = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['name', 'email'] def get_all_polls(self): pass def create_relationship(self, person): status, obj = Relationship.objects.get_or_create( to_person=person, from_person=self, ) return status def remove_relationship(self, person): Relationship.objects.filter( from_person=self, to_person=person ).delete() return 'dummy_value' def get_all_followings(self): return self.user.all() class Relationship(models.Model): from_person = models.ForeignKey(CustomUser, related_name='from_people', on_delete=models.CASCADE) to_person = models.ForeignKey(CustomUser, related_name='to_person', on_delete=models.CASCADE) And … -
List from key in Django QueryDict return one element instead of the whole list
I am using Django and I am accessing request.POST from my view. The code is as follows: data = request.POST print(data) Which returns: <QueryDict: {'name': ['Sam'], 'phone': ['+10795524594'], 'message': ['Es-sénia'], 'Coupon': [''], 'csrfmiddlewaretoken': ['xcGnoJOtnAmXcUBXe01t7ItuMC8BAFHE 6H9Egqd8BuooxLbp3ZrqvwzTZAxukMJW', 'xcGnoJOtnAmXcUBXe01t7ItuMC8BAFHE6H9Egqd8BuooxLbp3Zrq``vwzTZAxukMJW'], 'Size': ['S', 'M']}> But, whether using .dict() method or using data.get("Size"), I only get one element; not the whole list. How can I fix this? -
How can i link files to article model which uploaded by django-drf-filepond?
Info: I am using Django-drf-filepond in my django project for fileupload! django-drf-filepond has there two model TemporaryUpload(1) and StoredUpload(2). By defualt django-drf-filepond upload the files into TemporaryUpload before submiting the form. when user submit the form django-drf-filepond get data from TemporaryUpload and append it into StoredUpload model and remove it from TemporaryUpload model which data is appended into StoredUpload. What i want to do: When the user hit submit button the article is create and the appended files are linked with the article too. What I have so far: i have ArticleModel/ArticleForm. The article form data is submited and the files are appended into StoreUpload but the files are not linked it with an article. i want to linked it with article. when the user hit submit button. The data is submited by ajax. models.py class StoredUpload(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE, null=True) # This is the article model ForeignKey # The unique upload ID assigned to this file when it was originally upload_id = models.CharField( primary_key=True, max_length=22, validators=[MinLengthValidator(22)] ) file = models.FileField(storage=DrfFilePondStoredStorage(), max_length=2048) uploaded = models.DateTimeField() stored = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE ) def get_absolute_file_path(self): fsp = local_settings.FILE_STORE_PATH if not fsp: fsp = "" return os.path.join(fsp, … -
How to change english numbers to persian/arabic numbers in python
+1 9956755308 how to change this mobile number to persian or arabic numbers with unicode -
how to generate a qr code automatically when items are added in Django
here i want to automatically generate a unique qr code for each item when items are created in Django here is my models.py def qr_code_file_name(instance, filename): char_set = string.ascii_uppercase + string.digits dat = ''.join(random.sample(char_set*6, 12)) return 'qrimage/' + str(instance.client_id) + '/' + dat + '_' + re.sub(r'[^a-zA-Z0-9-_.]', r'_', filename); class Items(models.Model): client = models.ForeignKey("core.Client", related_name="job_items") item_name = models.CharField(max_length=512) cost_price = models.DecimalField(null=True, max_digits=10, decimal_places=2, default=0.00, verbose_name='Purchase price') common_name = models.CharField(max_length=512, blank=True, null=True) qr_code = models.ImageField(upload_to=qr_code_file_name, blank=True, null=True) Here is my forms.py class JobItemForm(BetterModelForm): def __init__(self, *args, **kwargs): self.client = kwargs.get("initial", {}).get("client") super(JobItemForm, self).__init__(*args, **kwargs) client = kwargs.get("initial", {}).get("client") ..... ..... def clean(self): cleaned_data = super(JobItemForm, self).clean() client = self.client pk = self.instance.pk name = cleaned_data.get('item_name') if pk is None: same_items = Items.objects.filter( item_name=name, client_id=client) if same_items.exists(): raise forms.ValidationError('The item with same name and part number already exists.') return cleaned_data class Meta: model = Items exclude = ('client') fields = ('item_name','common_name','cost_price','qr_code') Here is my views.py class JobItemCreateView(CustomAuthMixin, CreateView): model = Items form_class = JobItemForm context_object_name = "type" template_name = "jobs/jobitem_form.django.html" def get_initial(self): initial = super(JobItemCreateView, self).get_initial() initial['client'] = self.request.user.client initial['created_by'] = self.request.user return initial def form_valid(self, form): client = self.request.user.client self.object = form.save(commit=False) self.object.client = self.request.user.client with transaction.atomic(): self.object.save() messages.success(self.request, 'Item successfuly … -
I need a free static templates to build its back end, i need it like i am working in a team with front end and i am the back end
I need a free static templates to build its back end, I need it like I am working in a team with front end and I am the back end, how can I get a free template like this