Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model translation using gettext
There is little information on why to use gettext to translate content from the database what are its advantages and implications? Why hardly anyone talks about this? I see more information about: django-modeltranslation django-parler django-hvad Would it be more scalable to use django-vinaigrette? or are there some other alternatives? -
error during trying to connect to my server via ssh , can not connect to my vps server vis ssh
i've build a website using django and apache but today it suddenly raised an error when i try to open my website it show only Apache2 Ubuntu Default Page This is the default welcome page used to test the correct operation of the Apache2 server after installation on Ubuntu systems. It is based on the equivalent page on Debian etc .. before worked fine for about 9 month , i tried to connect to the server via ssh terminal ssh username@my_ip_address but it raised this error @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that a host key has just been changed. The fingerprint for the ECDSA key sent by the remote host is SHA256:the_key Please contact your system administrator. Add correct host key in /home/username/.ssh/known_hosts to get rid of this message. Offending ECDSA key in /home/username/.ssh/known_hosts:2 ECDSA host key for my_ip has changed and you have requested strict checking. Host key verification failed. and i run this command ssh-keygen -R my_ip and the output Host 51.83.98.146 found: line 2 /home/username/.ssh/known_hosts updated. Original contents retained … -
how to update the date?
when i'm updating the except all fields then updating well when i adding date field its not updating any data... plz let me know why.... forms.py class EmployeeForm(ModelForm): class Meta: model = Employee fields = "__all__" widgets = { 'edob': DateInput(), 'egender': forms.RadioSelect(), } models.py class Employee(models.Model): eid = models.CharField(max_length=20) ename = models.CharField(max_length=100) eemail = models.EmailField() econtact = models.CharField(max_length=15) esalary = models.CharField(max_length=100) egender = models.CharField(max_length=20, choices=G_CHOICES, default='male') edob = models.DateField() def __str__(self): return self.ename class Meta: db_table = "employee" update.html <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee DOB:</label> <div class="col-sm-4"> <input type="text" name="edob" id="id_edob" required maxlength="15" value="{{ employee.edob }}" /> </div> how to solve this didn't getting .... -
Django Rest Framework,Filtering objects based on Forignkey relationship
I have a simple Blog app where anyone can add post and comment to post. Comments have forignkey relationship with Post. When I select url patch posts/<post id>/comments it shows all comments instead of the comments from related posts. All other CRUD functions works fine with the project. The Git Link :https://github.com/Anoop-George/DjangoBlog.git The problem occurs in view.py where comment object unable to filter comments which are related to specific posts. class CommentListCreate(APIView): def get(self, request,pk): **comment = Comment.objects.filter()** # I need filter here serializer = CommentSerializers(comment, many=True) return Response(serializer.data) -
Django Rest Framework - Django ORM instance.delete() doesn't delete the instance...?
I have the following API delete view: @action(detail=True, methods=['delete'], permission_classes=[IsAuthenticatedViaJWTCookie]) def delete(self, request, pk=None, *args, **kwargs): queryset = self.get_queryset().get(id=pk) if queryset.user == request.user: queryset.delete() return Response(status=status.HTTP_204_NO_CONTENT) else: response = standardized_json_error_response( message='Artwork Object Could Not Be Deleted', data=[] ) return Response(data=response, status=status.HTTP_401_UNAUTHORIZED) When calling this view from an axios.delete request, I can see that the delete request is being made, and hitting the endpoint. All good so far. Yet, in the listing API view, the target instance to be deleted is still being listed. Doesn't matter how many times that endpoint is refreshed, or how long I wait. What is worse still, is when I call that endpoint again using axios.delete in the front end, for a second time, the record is then permanently deleted? Has anyone experienced such odd behaviour before with Django, or could this be a third party issue? *I have installed django-cleanup...? -
Heroku Debug Flag not stopping django debugging
I'm currently have Django project in heroku but I tried to stop the debug mode but unfortunately it's not working. First I tried to stop it from settings.py DEBUG=False DEBUG = os.environ.get('DEBUG', False) both not helping tried also to set env variable heroku config:set DEBUG=False heroku config:unset DEBUG both also not helping I tried to assign wrong value the debug in settings.py for testing which caused to crash the deployment. Hopefully some one can help with this. -
'ForwardManyToOneDescriptor' object has no attribute 'all
Now, i have problem w M2O relectionship :( Model.py class StorageDoc(models.Model): # tabela dokumentująca ruch na magazynie typeList = ( (' ', " "), ('WZ', "WZ"), ('PZ', "PZ"), ('PM', "PM") ) docType = models.CharField(max_length=10, choices=typeList, default=' ') storageName = models.ForeignKey(DictStorage, on_delete=models.DO_NOTHING) createTime = models.DateTimeField(auto_now=True) orderNumber = models.CharField(max_length=64, blank=True) class StorageDocPosition(models.Model): storageDoc = models.ForeignKey(StorageDoc, on_delete=models.DO_NOTHING, related_name="sds") item = models.ForeignKey(Part, on_delete=models.DO_NOTHING) volumeUsed = models.IntegerField() volumeBefore = models.IntegerField() volumeAfter = models.IntegerField() views.py def StorageDocList (request): s_documents = StorageDocPosition.objects.all().prefetch_related("storageDoc") for s_document in s_documents: s_documentP = StorageDocPosition.storageDoc.all() return render(request, 'StorageDocList.html', {'storageDocAll': s_documents}) my error is: 'ForwardManyToOneDescriptor' object has no attribute 'all' why I can not use "all" in this case? How fix it? Thanks for help : -
Why doesn't Django detect the Summernote module?
So I'm currently using Django ver. 3.x, and trying to load summernote on my webpage. I'm using Bootstrap4 btw. I've done exactly the same as written in https://github.com/summernote/django-summernote. However, when I execute python manage.py makemigrations after migration, I get this error : "ModuleNotFoundError: No module named 'django-summernote'" Below is the full error script. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\user\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\user\Envs\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Envs\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\user\Envs\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\user\Envs\venv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django-summernote' I don't see what I've done wrong. I would very much appreciate your help. :) -
Child class inherits from concrete parent: django.db.utils.OperationalError: foreign key mismatch
I have a concrete parent class Sub and a child class SubOrder. One Sub can "have" (i.e. be in ) many SubOrders and one SubOrder can "have" (contain) many Subs. My classes are as below, but when I try to create a Sub-object, I get the error: django.db.utils.OperationalError: foreign key mismatch - "orders_suborder" referencing "orders_sub" What's the issue here? Do I need to use ManyToManyField (if so, why & where?) and why am I getting this error? class Sub(Dish): dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_sub", parent_link=True) def __str__(self): return f"{self.name}, Price: ${self.price}" class SubOrder(Sub): sub_id = models.ForeignKey(Sub, related_name="sub_id", parent_link=True) item_id = models.ForeignKey(Item, on_delete=models.CASCADE, primary_key=True, related_name="sub_item_id") extra_count = models.IntegerField(default=0, validators=[MaxValueValidator(4), MinValueValidator(0)]) MUSHIES = 'M' PEPPERS = 'P' ONIONS = 'O' XTRCHEESE = 'C' EXTRA_CHOICES = ((MUSHIES, 'Mushrooms'), (PEPPERS, 'Peppers'), (ONIONS, 'Onions'), (XTRCHEESE, 'Extra Cheese'),) extra_1 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True) extra_2 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True) extra_3 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True) extra_4 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True) def __str__(self): extras = [] for i in range(extra_count): str = "extra_"+i extras.append(str) return f"Sub Order: Item {self.item_id}, {self.name}, size: {self.size}. {self.extra_count} Extras: {extras}" If it matters, here's the Sub's parent class Dish, but I don't think that's the issue: class Dish(models.Model): PIZZA = 'PIZZA' SUB = 'SUB' … -
Django isn't recognizing that a user has been authenticated after loggin in. I have to refresh the page one more time before it goes through
As the title states when I login and put in my credentials it redirects me to an html page where I have a condition of and it evaluates this to False. {% if user.is_authenticated %} However when I refresh the page it evaluates this condition to true even though I haven't done anything. Any possible explanations or solutions this? Thank you for any and all help! -
Django, display form based on value of another form
I'm trying to show or hide a crispy form based on the value of other form. I have the following form: <div class="form-group col-2 0 mb-0" id="field_three"> {{form.numero_mensilità|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0 d-none" id="field_four"> {{form.mese_pagamento_13|as_crispy_field}} </div> I want that when client digit in the first form (id=field_three) the value 13, automatically django show me the second form (id="field_four"). These will be happen during the filling of the form, so if the client change the value from 13 to 12 ad example, the field disappears. I have tried to perform this script but does not work: // this is executed once when the page loads $(document).ready(function() { // set things up so my function will be called when field_three changes $('#field_three').change( function() { check_field_value(this.value); }); // function that hides/shows field_four based upon field_three value function check_field_value(new_val) { if(new_val != '13') { // #id_field_four should be actually the id of the HTML element // that surrounds everything you want to hide. Since you did // not post your HTML I can't finish this part for you. $('#field_four').removeClass('d-none'); } else { $('#field_four').addClass('d-none'); } } -
Django SSE and Websocket
I want to use Webscokets and SSE in django, I know i can do it with ASGI, uWSGI and for WebSockets Django Channels. My question is what is the difference between ASGI an uWSGI and which one is better solution in 2020 -
Django model attributes not getting displayed in html page
Apologies for the noobish question, I am new to Django and trying to make an e-commerce app. What I want to do, is that show users variations available for an item in the product page. I've created a model for variations, and added some variations in my admin panel, but when I'm trying to display those, it is not happening. I think the way I'm accessing it is wrong. Can anyone please help me solve the problem? Thanks in advance! My models.py: class Item(models.Model): title = models.CharField(max_length=120) price = models.FloatField() class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) name = models.CharField(max_length=50) # size, color class Meta: unique_together = ( ('item', 'name') ) class ItemVariation(models.Model): variation = models.ForeignKey(Variation, on_delete=models.CASCADE) value = models.CharField(max_length=50) # small, medium large etc class Meta: unique_together = ( ('variation', 'value') ) My sinngle_product.html: The form part <h1 class="product-title">{{ item.title }}</h1> <a href="#"> <span class="badge purple mr-1">{{ object.get_category_display }}</span> </a> <span class="review-no text-danger">41 reviews</span> </div> {% if object.discount_price %} <h4 class="price">price: <del><span>${{ object.price }}</span></h4></del> <h4 class="price text-primary">current price: <span>${{ object.discount_price }}</span> <span class="badge badge-pill badge-warning">Limited Time Offer!</span> {% else %} <h4 class="price">current price: <span>${{ object.price }}</span> {% endif %} <p class="vote text-success"><strong>91%</strong> of buyers enjoyed this product! <strong>(87 votes)</strong></p> <form … -
GraphQL API export of Django project in SDL representation not possible anymore
I'm trying to export the GraphQL API of my backend server with python manage.py graphql_schema --schema <django-app>.schema.schema --out <django-project>/schema.graphql. The generated file contains the introspectable representation like exported with ... --out schema.json. I was able to output the SDL representation of this project before. It seems like a package I introduced later is the root cause ot this issue. I added the following GraphQL dependencies over time: graphene==2.1.8 graphene-django==2.8.0 graphene-django-cud==0.4.4 graphene-file-upload==1.2.2 graphene-subscriptions==1.0.2 graphql-core==2.3.1 graphql-relay==2.0.1 Had someone else this behavior as well and knows how to fix or workaround it? -
what is benefit of using Redis for my Django web app?
Actually i created a simple web app with Django. I want to use server-push functionality in my web app. I think this type of functionality can be achieved through WebSockets using Django-channels. But if I want to use WebSockets in Django-channels then I also need to run Redis server parallel as well but why I need to run Redis server.what is the use of Redis with Django-server I'm so confused. -
'Django-admin not recognized as a command'
So I wanted to try Django and as the tutorial said I went ahead and installed virtualenv. I create the venv and cd into it. Then i try to create a project inside it but i cant. I put the file inside PATH and tried once again "django-admin startproject [name of my project]" and got this error: 'django-admin' is not recognized as an internal or external command, operable program or batch file. And i know there are a couple of simular forums here on stack overflow already but as far as i saw nothing worked. -
how to combine or integrate reactjs and Django
I created front end in Reactjs and backend in Django and linked using Django rest API. but react runs in localhost:3000 and Django in localhost:8000. How to combine or integrate these two and runs in the same address. -
How do i set the length of like counts
i am new on Django and i am working on a website where users like posts. I have an issue on how i can set the length of like counts before 'Likes' will be removed and show only the like counts. When a user do not click on Like button it displays 'LIKE' at the side of like button, but when a user clicked on the like button it displays the like count to 1 without 'LIKE' at the side of the count, because i am using an else statement. How do i display 'LIKE' at the side of like count. For example; '1 Liked' Then when 100 users clicked on like button, like counts: '100'. But if it is less than 100, like count will be '99 Liked' enter image description here {% if post.liked_by_user %} <button type="submit" name="post_id" value="{{ post.id }}" class="like float-left pl-2" > <img src="{{ '/static/' }}images/heart_empty.png" width="24" height="24"> </button> {% if post.likes.all %} <a href="{% url 'site:likes_users' post.id %}" class="like-count font-small dark-grey-text font-weight-bold"> <span class="d-inline-block text-truncate" style="max-width:70px;position:relative;top:3px;"> {{ post.likes.count }} </span> </a> {% else %} <span class="like-count font-small dark-grey-text font-weight-bold">Like</span> {% endif %} {% endif %} -
How to refactor Django code automatically?
I have changed column name of a table. How can I automatically trigger refactoring so that all old name reference in my app is replaced by new name? -
React-Native post geometry object to a GIS database via Django API
I am trying to use axios to create a post to a GIS database that is created using Django. The problem is that I have a geometry point in my model and in my front-end app I only have the coordinates. So now, my question is how to create a POST request to a table that contains Geometry object? Here is what I have for the moment: Django model: class Place(geomodel.Model): place_name = geomodel.CharField(max_length=256) description = geomodel.TextField(blank=True) picture = models.ImageField(blank=True) place_type = models.ForeignKey(PlaceType, on_delete=models.CASCADE) geom = geomodel.PointField() approved = models.BooleanField(default=False) telephone = models.CharField(max_length=256) rating = models.IntegerField() numberOfVotes = models.IntegerField() createdBy = models.ForeignKey(RegisteredUsers, on_delete=models.CASCADE) def __str__(self): return self.place_name Django serializer: PlaceSerializer(GeoFeatureModelSerializer): place_comments = CommentSerializer(many = True, required=False) dis = serializers.DecimalField(source='distance.m', required=False, read_only=True, max_digits=10, decimal_places=2) class Meta: model = Place geo_field = "geom" fields = ("id", "place_name", 'description', 'picture', 'place_type', 'dis', 'approved', 'place_comments') Django view: PlaceViewSet(viewsets.ModelViewSet): queryset = Place.objects.all().filter(approved=True) serializer_class=DogPlaceSerializer def get_queryset(self): qs = super().get_queryset() latitude = self.request.query_params.get('lat', None) longitude = self.request.query_params.get('lng', None) distance = self.request.query_params.get('dist', None) if latitude and longitude: pnt = geos.GEOSGeometry('POINT(' + str(longitude) + ' ' + str(latitude) + ')', srid=4326) if distance: qs = DogPlace.objects.all().filter(geom__dwithin=(pnt, distance)) qs = qs.annotate(distance=Distance('geom', pnt)).order_by('distance') return qs and in the front end: const … -
Customer instance has invalid ID: None, <class 'NoneType'>. ID should be of type `str` (or `unicode`)
am trying to create a stripe card but am having this error "Could not determine which URL to request: Customer instance has invalid ID: None, . ID should be of type str (or unicode)" this is my view.py ''' def index(request): # if request.user.is_authenticated: # billing_profile=request.user.billingprofile # my_customer_id=billing_profile.customer_id billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) if not billing_profile: return redirect("carts:cart_view ") next_url = None next_ = request.GET.get('next') if is_safe_url(next_, request.get_host()): next_url=next_ return render(request, 'my_index.html',{"next_url":next_url}) def charge(request): if request.method == 'POST': print('Data:', request.POST) # stripe.Customer.create( # email=request.POST['email'], # # ) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) token = request.POST.get('stripeToken') if token is not None: customer = stripe.Customer.retrieve(billing_profile.customer_id) card_response=customer.sources.create(source=token) print(card_response) return redirect(reverse('Payments:success')) def successMsg(request): return render(request, 'my_success.html') this is my model.py class BillingProfileManager(models.Manager): def new_or_get(self,request): user=request.user guest_email_id = request.session.get('guest_email_id') created=False obj=None if user.is_authenticated: # logged in user checkout ;remember payement stuff obj, created=self.model.objects.get_or_create( user=user, email=user.email ) elif guest_email_id is not None: # logged in user checkout, auto reload payement stuff guest_email_obj = GuestEmail.objects.get(id=guest_email_id) obj, created = BillingProfile.objects.get_or_create( email=guest_email_obj.email) else: pass return obj,created class BillingProfile(models.Model): user=models.OneToOneField(User,unique=True,null=True,blank=True,on_delete='CASCADE') email=models.EmailField() active=models.BooleanField(default=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) customer_id=models.CharField(max_length=120,null=True,blank=True) objects=BillingProfileManager() def __str__(self): return self.email def billing_profile_created_receiver(sender,instance,*args,**kwargs): if not instance.customer_id and instance.email and instance.user: print("Actual api request send to stripe/braintree") customer=stripe.Customer.create( email=instance.email, name=instance.user, … -
Django Rest Framework default_authentication_classes setting
I am using Django Rest Framework (3.11) with Django (3.0). I have successfully implemented JWT authentication for my API. In the settings.py file, I have the following: # Rest framework configuration REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSIONS_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } Removing 'rest_framework.authentication.BasicAuthentication', results in the following error when hitting any of the endpoints in the API: TypeError at / 'type' object is not iterable Does this mean the BasicAuthentication class is required for the application to run? Or is this not normal and I have a configured something incorrectly somewhere? -
Django - Static files partially loading
I have the following static folder in my Django project: On all of my html pages, I write the following: {% extends "app_base.html" %} {% load static %} {% block app %} When I run server, the static pages load partially, I know this by inspecting element on chrome: I tried running $ python manage.py collectstatic mentioned in the docs, didn't help. I can load each static file individually as in: {% load static %} <script src="{% static 'js/my.js' %}"></script> I've had django projects in the past where { % load static % } is all i need, curious why it isn't working in this instance. -
Nested Query / not directly related field in Django
If the models are as follows, class Subject(BaseModel): name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) class Meta: managed = True db_table = 'Subject' class Topic(BaseModel): name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, null=False, related_name='subject_topic') class Meta: managed = True db_table = 'Topic' class Question(BaseModel): topic = models.ForeignKey(Topic, on_delete=models.CASCADE, null=False, related_name='question_topic') class Meta: managed = True db_table = 'Question' How can I make a query Question for a subject. questions = Question.objects.filter(topic_in=Topic.objects.get(subject=subject).only('id').all()) but it's not working. Any help would be really great help. -
How to run management commands from the Django admin dashboard
I have created some of my custom management commands in Django, so my question here is how to run those commands from the admin interface.