Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
update only targeted element with ajax
I'm trying to update my cart page with ajax when someone increases or decreases the quantity of the products, my view logic is fine. My issue as I can infer is targeting the class "ajax_updater", as soon as I hit the quantity buttons ajax works, but instead on just the specific product, it targets all the products' quantity with the same class ".quantity-style" and changes the value as per the targeted product, so, if the quantity for product A is 4 after ClickEvent, the quantity for product B, D, F gets targeted and changed to 4 too, what could be a solution? {% for item in items %} <div class="quantity"> <p id="quantity-style" class="quantity-style">{{item.quantity}}</p> <div class="quantity-arrows"> <img data-product="{{item.product.id}}" class="ajax_updater" data-action="add" src="{% static 'shop/images/arrow-up.png' %}"> <img data-product="{{item.product.id}}" class="ajax_updater" data-action="remove" src="{% static 'shop/images/arrow-down.png' %}"> </div> </div> {% endfor %} function update_arrow() { $.ajaxSetup ({ cache: false }); var spinner = '<i class="fas fa-circle-notch fa-spin" style="font-size:15px;" alt="loading" ></i>'; $(".quantity-style").html(spinner).load(update_quantity_url); console.log(update_arrow_url); } $('.ajax_updater').click(function () { update_arrow(); console.log('hit hit'); }); -
What is the difference between SimpleTestCase.settings() and django.test.override_settings?
Django provides different ways to change settings(documentations) in a test in different levels (TestCase class, test method, context manager). I understand the difference between override_settings and modify_settings, but I can't get the difference between SimpleTestCase.settings() and django.test.override_settings() when being used as a context manager. Is there any difference in functionality or preference in which one to use? -
(Django / Nginx / Gunicorn) HTTPS fails to serve pathed directories on my site
Pretty new to Nginx and web deployment in general. I have a site I am aiming to deploy using a DigitalOcean droplet. Right now it is working, but only with http://[SERVER-IP] (here) Although the site does load with HTTPS (here), no domain.com/[ X ] sites work. The aim is to make get all URLs within https://rejesto.com functioning normally and leading to their respective sites. For context, all links on the page are provided by Djagno's {% url '[url]' %} tag system; they work as intended locally, and using http://[SERVER-IP]/[ X ]. I'm assuming that the issue is within the Nginx config files because: http://46.101.92.95/blog leads to the correct page. (for better or for worse) https://rejesto.com/blog does not work. Here is (what I believe to be) the relevant config file: /etc/nginx/sites-available/rejesto.com: server { server_name rejesto.com www.rejesto.com; location / { try_files $uri $uri/ =404; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/rejesto/myprojectdir; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/rejesto.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/rejesto.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by … -
UpdateAPIView | Django REST does not update data properly
I want to register values in a table of relations when updating data. Conversely, I want to generate an error if the value does not exist. models.py class CustomUser(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) email = models.EmailField(_('email address'), unique=True) role = models.OneToOneField('Role', related_name='user', blank=True, null=True, on_delete=models.PROTECT) # ommited... class Role(models.Model): slug = models.SlugField(unique=True) def __str__(self): return self.slug serializers.py from drf_writable_nested import WritableNestedModelSerializer from rest_framework import serializers from accounts.models import CustomUser, Role class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ('slug',) class UserSerializer(WritableNestedModelSerializer): role = RoleSerializer() class Meta: model = CustomUser fields = ('uuid', 'email', 'role', 'password') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): return CustomUser.objects.create_user(**validated_data) views.py class UserUpdateView(generics.UpdateAPIView): queryset = CustomUser.objects.all() serializer_class = UserSerializer Role DB Table id:1 | slug:admin Expectation Request(PATCH) Parameter { "role":{ "slug":"foo" } } # error: foo does not exist in the Role table { "role":{ "slug":"admin" } } # OK!!! What should I do? Thank you very much. -
How to obtain a specific data from model in profile when person is logged in, Django?
I want to post a specific data in profile from user that is logged in. I have a model like this: class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=60) email = models.EmailField(max_length=100) class Wallet(models.Model): name = models.OneToOneField(User, null=True, on_delete=models.CASCADE) usd = models.FloatField(null=True) If for example 'user2' is logged in, and in database he has 10usd, I want in his profile to be shown 10usd. But I don't know how to request a specific data of user that is logged in Views.py @login_required(login_url='main') def profile_user(request): usd = wallet.objects.get (get his usd from db) return render(request, 'profile.html', {'usd':usd}) Thank you very much. -
Issue deploying Django webapp in OVH Hosting
I'm trying to deploy a Django App in OVH Hosting and, after some hard exploration and try-error, I keep getting an issue. File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 381, in <module> handler = RequestHandler(server_socket, sys.stdin, app_module.application) AttributeError: module 'passenger_wsgi' has no attribute 'application' OVH/Passenger proccess feedback Apart from all the files created at startapp by Django and all the code I wrote I added the following file 'passenger_wsgi.py' on the root of the app directory. I used two differents versions: First: import MyApp.wsgi application = MyApp.wsgi.application Second: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() In the runtime configuration of OVH hosting the application launch script set is 'manage.py'. SECRET_KEY and DJANGO_SETTINGS_MODULE are declared in the environment variables. -
How can I find 3 top or max value in django model?
I have a class in django model and how can I find 3 maximum value in it? Do I need for into for loop? or Do I need any class? class Prices (models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) Price = models.IntegerField() page = models.ManyToManyField(Listing_page,blank=True,related_name='Price') def __str__(self) -> str: return f"{self.id} : {self.Price}" I have follow code for top price but I need 3 top price too. big_price = None for num in post.Price.all(): if (big_price is None or num.Price > big_price.Price): big_price = num -
Using the URLconf defined in name, Django tried these URL patterns, in this order
I have a django project and in this project I have two apps: main and profiles. So I added both mini apps to the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'profiles', ] and I can run the main application - if I go to: http://127.0.0.1:8000/ It is running. But If I go to: http://127.0.0.1:8000/profiles Then I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/profiles Using the URLconf defined in schoolfruitnvwa.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, profiles, didn’t match any of these. So my question is: how to tackle this? Thank you -
How to mark words that match words from a list in a django form's textarea using javascript?
I have the following form: class TestForm(Form): testfield = CharField(widget=Textarea(attrs={'rows': 10, 'id': 'test'}), label='Input test text here') Rendered to my template along with the following list as context: dummy_list = ['hi', 'hello'] I'm trying to make a button which I can click in my template which makes words in the form bold if they are contained within the list. JS: <script type="text/javascript"> function Mark_words(id) { var form_content = document.getElementById(id); var dummylist = {{ dummy_list }} var new_form_content = "" for(var x in form_content.value) { if ( dummylist.indexOf(x) > -1 ){ x = x.bold(); new_form_content += x + " "; } else { new_form_content += x + " "; } } form_content.innerText = new_form_content; } </script> And the following button: <button type = "submit" class ="btn btn-info" value = "Click" onclick="Mark_words('test')">Mark words</button> Unfortunately, nothing happens when I click the button. What am I doing wrong? -
Django: relations between two objects of the same model
I have created this model: class Process(models.Model): name = models.CharField('Process name', max_length=50, unique=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, max_length=50, null=True, verbose_name='Process owner') I want to create multiple processes and from those build a hierarchy. Here is a hierarchy model: class Hierarchy(models.Model): name = models.ForeignKey('process.Process', on_delete=models.CASCADE, verbose_name='Sub process name') name = models.ForeignKey('process.Process', on_delete=models.CASCADE, verbose_name='Main process name') order = models.IntegerField('Process order', default='1') Obviously this doesn't work as the 'name' fields in hierarchy model interfere with each other. I wouldn't want to create models MainProcess and SubProcess as some SubProcesses might have more SubProcesses etc. What would be the right way to build this type of model/hierarchy? This might be very basic issue, but I couldn't find any related issues to apply a solution from, so any help would be appreciated. -
XXX is not defined - Importing Class from OpenLayers Node Module in Django
Having difficulty getting the Node OpenLayers to work within Django. npm and ol are installed and the files are in a node_modules folder in my project. I included the node_modules folder in my STATICFILES_DIRS in settings.py. I'm including the OpenLayers modules within my template, map.html: <script type="module" src="{% static 'ol/dist/ol.js' %}"></script> <script type="module" src="{% static 'ol/Map.js' %}"></script> <script type="module" src="{% static 'ol/View.js' %}"></script> <script type="module" src="{% static 'ol/layer/Tile.js' %}"></script> <script type="module" src="{% static 'ol/source/OSM.js' %}"></script> <script type="text/javascript"> import "{% static 'ol/layer/Tile.js' %}"; const map = new ol.Map({ target: 'my-map', layers: [ new ol.Layer.Tile({ source: ol.Source.OSM() }) ], view: new ol.View({ center: [40, -70], zoom: 2 }) }); </script> Which appears to be working as I can see the files load within my browser's dev tools. But when I try to use the classes within the modules I get the error: Uncaught ReferenceError: ol is not defined OTHER METHODS I'VE TRIED: I've also tried calling the class names directly: <script type="text/javascript"> const map = new Map({ target: 'my-map', layers: [ new Tile({ source: OSM() }) ], view: new View({ center: [40, -70], zoom: 2 }) }); </script> But get the same error: Uncaught ReferenceError: Tile is not defined The OpenLayers docs … -
Wagtail dumpdata modellogentry null values
Having a problem with dumpdata command in Wagtail v.3.0.3. Some of the entries for the table pagelogentry have data set to null and not the expected {}. It is not all the values. When I do dumpdata I have to edit the dump file by hand to allow it to work with loaddata. e.g. { "model": "wagtailcore.pagelogentry", "pk": 2, "fields": { "content_type": [ "home", "gallerypage" ], "label": "Excellence in Engineering", "action": "wagtail.publish", "data": null, "timestamp": "2020-08-18T16:25:08.456Z", "uuid": null, "user": [ "egomez" ], "content_changed": true, "deleted": false, "page": 2702, "revision": 7602 } } We have had this site for a few years and it has been updated through various Wagtail versions. I'm not sure what the right course to fix the data is here. -
django How do I get a value from a model recursive reference?
I am trying to implement the comment function of comments through self reference. error: models.ReComment.DoesNotExist: ReComment matching query does not exist. Parent_comment of ReComment model was ForeignKey as self I printed self.kwarg and got a value of {'pk': 3, 'comment_id': 8} models.py class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() feeling = models.CharField(max_length=50, validators=[validate_no_numbers, validate_no_special_characters]) score = models.IntegerField(validators=[validate_score, validate_no_special_characters]) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") likes = GenericRelation("Like", related_query_name="post") def __str__(self): return self.title class Comment(models.Model): content = models.TextField(max_length=500, blank=False) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") likes = GenericRelation("Like", related_query_name="comment") def __str__(self): return self.content[:30] class ReComment(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name="recomments") content = models.TextField(max_length=500, blank=False) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) parent_comment = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE, related_name="parent_comments") def __str__(self): return self.content[:30] form.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "content", ] widget = { 'content': forms.Textarea, } class ReCommentForm(forms.ModelForm): class Meta: model = ReComment fields = [ "content", ] views.py class CommentCreateView(LoginAndVerificationRequiredMixin, CreateView): http_method_names = ["post"] model = Comment form_class = CommentForm def form_valid(self, form): form.instance.author = self.request.user form.instance.post = Post.objects.get(id=self.kwargs.get("pk")) return super().form_valid(form) def get_success_url(self): return reverse("post-detail", kwargs={"pk":self.kwargs.get("pk")}) class ReCommentCreateView(LoginAndVerificationRequiredMixin, CreateView): http_method_names … -
Wagtail PageRevision errors from loaddata
When I use dumpdata / loaddata to snapshot my live Wagtail sites to my sandbox, I sometimes get pages which I can't edit on my sandbox. These are always pages which the Wagtail admin explorer has marked "live + draft". They produce a 500 error, can't currently handle on_delete types other than CASCADE, SET_NULL and DO_NOTHING but the stack trace shows the cause is a ContentType matching query does not exist. The only way to make them editable on the sandbox is to remove the PageRevision for each of the pages locally, via Django/python shell. Is there an approved way to fix these pages to remove the spurious drafts? -
Error converting data type nvarchar to Datetime While Calling Store Procedure in Django
I am trying to pass datetime value to the store procedure of mssql but getting this error: django.db.utils.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to datetime. (8114) (SQLExecDirectW)') Here is the code: fromDate = datetime(2022, 1, 1) toDate = datetime(2022, 12, 31) dealershipId = request.GET['dealershipId'] cursor = connection.cursor() cursor.execute(f"EXEC proc_LoadJobCardbyDateRange [@Fromdate={fromDate}, @Todate={toDate}, @DealershipId={dealershipId}]") result = cursor.fetchall() I have tried to pass datetime object in order to execute store procedure. I also tried to pass datetime as string but the same error persists. I also tried different formats but it didn't work as mentioned in some solutions that I have searched for. Please guide me as to why I am having this issue and what's the correct solution to this can be? -
Django password hashing different from python passlib pbkdf2 library
Using django admin, I have created a user email: cuteemail@example.com password: ccpass!ccpass The hashed password stored in the database is pbkdf2_sha256$260000$alGB1h2BRHwn83nz9fSJ3V$qippfbL8g59KPoDh+cIEh70TQCjuWeH8017VcLLpDIY= All I know is that django is generating the password hash using PBKDF2 algorithm. I need to run a pure python script that inside a part of it, it checks if a password is matching a hash. I have found a library passlib. I can provide the password and rounds. But where does the django salt come from? from passlib.hash import pbkdf2_sha256 password = 'ccpass!ccpass' db_hashed_password = 'pbkdf2_sha256$260000$alGB1h2BRHwn83nz9fSJ3V$qippfbL8g59KPoDh+cIEh70TQCjuWeH8017VcLLpDIY=' salt = db_hashed_password.split('$')[2].encode() pbkdf2_sha256.hash(password, rounds=260000, salt=salt) result: $pbkdf2-sha256$260000$YWxHQjFoMkJSSHduODNuejlmU0ozVg$qippfbL8g59KPoDh.cIEh70TQCjuWeH8017VcLLpDIY The resulted password hash apparently looks the same except minor differences. The pbkdf2-sha256 has a dash instead of an underscore but this is not a problem. I can fix it. The main problem is that I do receive a . instead of + in the actual hash part. How to fix this? Can I blindly replace all . with + ? -
Django Rest Framework - datetime sent as str gets changed to different timezone when being saved to database?
I sent the following: {'ticker': 'XYZ', 'last_price': 394.05, 'last_date_time': '2022-10-04 15:57:18'} When it was saved in DB: ticker: XYZ last_price: 394.05 last_date_time: 2022-10-04 11:57:18 I am not sure how or why this gets changed. models.py class StockPriceModel(models.Model): ticker = models.CharField(max_length=30, blank=False, db_index=True) last_price = models.FloatField(blank=True, null=True) last_date_time = models.DateTimeField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) The auto_now_add field is also showing incorrect time. It doesn't correspond to my date time setup in settings as below: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Dubai' USE_I18N = True USE_L10N = True USE_TZ = True -
difference between Django ORM datetime and Postgre datetime value
I have developed an application with Django and recently changed my DB from Sqlite to Postgresql. I have found the following inconsistency between datetime values in DB and results of Django orm: and: You can see the difference between hours, mins and seconds. It should be noted that the column type is datetime and there is not any inconsistency if i use sqlite. -
How to join two different modal in django?
I'm using django 3.2. And DB name postgres. I'm stuck in a problem where i want to combine two modals. I have following two modals 1- Profiles 2- Ratings foreignKey(Profiles) now I want to return profiles list with their ratings. And this is what i'm unable to achieve. Actually I don't know how to do that. I think it can be done by inner join by profile_id but how to do this with django ? My code : @api_view(['GET']) @permission_classes([IsAuthenticated]) def profile_list(request): if request.method=="GET": kind = kind.lower() paginator = CustomPagination() paginator.page_size = 10 print("dat da da da da ==>> ",request.data) coordinates = request.data["coordinates"] nearby_count = Profile.objects.nearby_count(coordinates) total_count = nearby_count total_page = total_page_counter(nearby_count) profiles_queryset = Profile.objects.nearby_ground_list(coordinates) ## Rating.objects ???? page_data_of_profiles=None try: page_data_of_profiles = paginator.paginate_queryset(profiles_queryset, request) except: pass serializer = ProfileSerializer(page_data_of_profiles, many=True) return Response({"status":"success","message": "Ok","total_count":total_count,"total_page":total_page, "data": serializer.data},status=status.HTTP_200_OK) -
how i make a qr code generator in django?
I'm working on an existing project with Django and I need to add a qr code that generate the profile info from database , but unfortunately I didn't find a helping documentation so if u have any idea of what I'm facing hit me up with an advice or a link and thank you -
Django AWS cannot be access from public IP
I've been trying to put my Django application as docker in AWS ECS and it works as intended when accessing from inside. Then I tried to add an ALB so I can access my application but so far failed to do so. I have exposed port 8000 in docker where my application runs and in task definition mapped it to port 80 in host. It's up and running as a ECS cluster service where the VPC subnet choice is the same as in the ALB. My ALB is listening to both 80 and 8000 ports and forwarding to the target group which also has port 80. I have used a single security group for this allowing both ports with all IPs I'm struggling to figuring out what went wrong here. -
Django Action Append Slash
I am making development, and my POST request come like config/alert and I am trying to catch it with action decorater below.BUT Django does not catch it It wants config/alert/ but It is not possible to change incoming url add the SLASH. @action(methods=['post'], detail=False, url_path='alert') def get_post(self, request, pk=None, *args, **kwargs): How can I modify the action to listen without slash in POST request? -
Error in activation via URL sent to email in user registration system using DRF
I wanted to add a registration system to the API using DRF. The user receives an activation url by email and can activate his account. I am having problems decoding this sent token, i.e. it is taking the token as invalid. views.py I created a registration system and followed it up with an activation system. class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absolute_url = "http://" + current_site + relativeLink + "?token=" + str(token) email_body = "Hi " + user.username + ". Use link below to verify your email \n" + absolute_url data = {"email_body": email_body, "to_email": user.email, "email_subject": "Verify Your Email"} Util.send_email(data) return Response(user_data, status=status.HTTP_201_CREATED) class VerifyEmail(views.APIView): serializer_class = EmailVerificationSerializer token_param_config = openapi.Parameter( 'token', in_=openapi.IN_QUERY, description='Description', type=openapi.TYPE_STRING) @swagger_auto_schema(manual_parameters=[token_param_config]) def get(self, request, *args, **kwargs): token = request.GET.get("token") try: payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) if not user.is_verified: user.is_verified = True user.save() return Response({"email": "Successfully activated"}, status=status.HTTP_200_OK) except jwt.ExpiredSignatureError: return Response({'error': 'Activation expired'}, status=status.HTTP_400_BAD_REQUEST) except jwt.exceptions.DecodeError: return Response({"error": "Invalid token"}, status=status.HTTP_400_BAD_REQUEST) serializers.py from rest_framework import serializers from .models import User class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(min_length=6, max_length=50, write_only=True) … -
why Django redirect function returns to the same page
I have a website where there are different groups. As soon as you click on one of the groups, you are redirected to the details page of that group. This click happens via a post method, where the name of the group is sent to the server. There I check if it is a POST method, and since I use several on the page, I also check which one it is ['post-function']. Then the name of the group is stored in the session (this is important for a later function). Afterwards it should be redirected to the detail page. However, I always end up on the same page. In the console I can see that the details page is loading, but I am somehow redirected to the main page. these are my URLS: urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='home'), path('send', send, name='send'), path('datasheet/', datasheet, name='datasheet'), path('datasheet/intents/', intents, name='intents'), ] datasheet is the page where all the groups are listed and can be clicked for the detail page here are my views: def datasheet(request): # error handling if 'error' not in request.session: error = "no_error" else: error = request.session['error'] del request.session['error'] # post methods if request.method == 'POST': # … -
Foreign Key USER Django Model: django.db.utils.IntegrityError: (1062, "Duplicate entry
I'm trying to use User as a foreign key for Time for an API, but I'm getting this error message when I try to add another time django.db.utils.IntegrityError: (1062, "Duplicate entry '20' for key 'time.user_id'") My model: class Time(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING) start = models.CharField(max_length=10, default=None, null=True, blank=True) end = models.CharField(max_length=10, default=None, null=True, blank=True) My view: @api_view(['POST']) def TimeNew(request, email): try: user = User.objects.get(email=email) except User.DoesNotExist: return JsonResponse({'message': 'ERRO'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'POST': time_data = JSONParser().parse(request) time_data['user'] = user.id time_serializer = TimeSerializer(data=time_data) if time_serializer.is_valid(): time_serializer.save() return JsonResponse(time_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(time_serializer.errors, status=status.HTTP_400_BAD_REQUEST)