Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I change requested password to two parameters named as `salt` and `pwdhash` and save it to database in django?
I have a model named as userspasswords. model definition is sth like this: pice of code in models.py class UsersPasswords(models.Model): user = models.ForeignKey( Users, related_name='id_user_password', on_delete=models.DO_NOTHING) salt = models.CharField(max_length=200, blank=True) pwdhash = models.CharField(max_length=200, blank=True) inserted_timestamp = models.DateTimeField(auto_now_add=True) pwd_creator = models.ForeignKey( Users, related_name='pwdcreator_user_details', on_delete=models.DO_NOTHING) class Meta: ordering = ('user_id',) I also write a serializer in serializers.py: class UsersPasswordsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) pwd_creator = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) class Meta: model = UsersPasswords fields = ( 'pk', 'user', 'salt', 'pwdhash', 'inserted_timestamp', 'pwd_creator' ) And also I create a view in views.py: class UserPasswordsDetail(generics.RetrieveUpdateDestroyAPIView): queryset = UsersPasswords.objects.all() serializer_class = UsersPasswordsSerializer name = 'userpasswords-detail' But what is the problem? I intended to change received JSON data from POST method and save it to database like this. received data : user, password manipulate data and save with these fields: pk, user, salt, pwdhash, inserted_timestamp, pwd_creator I have some functions to create hash and salt values and also check password validation using hash and salt. here is all my functions located in myCryptography.py: from hashlib import pbkdf2_hmac from flask import jsonify import jwt import datetime import secrets from app import salt, pwdhash, token def pbkdf2_hmac_sha512(password, salt, iters=2048): # Create hash return pbkdf2_hmac(hash_name='sha512', password=password, … -
Pinax-referrals, how to remove the the domain name from generated referral link and connect it to a view
Hellow guyz, am working on pinax-referrals intergrating it with my Django app. SO far i have managed to generate referral code for every user that has signed up. my problem is that, when i output those refferal link generated for a user, it brings a domain name that is http://example.com/referrals/iqtK4SBNWcE59TN2E2oCbRZcS4ui1sadtO8iHyB3/. How can i remove that domain name(example.com) and replace it with the domain name of my local host domain(127.0.0.1:8000). Also from the above, i have created a view which welcomes a user who has joined using a referral link. i want the view to display the name of the referrer, something like, "welcome, you have been invited by {{ the username of the referrer }} ". But am having a challenge to connect that referral link to my welcome view for the referred users. i have tried to search the pinax-referral documentation but it is not bringing it out clearly for a newbee like me to understand well. any help so please signals.py from allauth.account.signals import user_signed_up from .models import Profile from pinax.referrals.models import Referral @receiver(user_signed_up) def save_profile(sender, **kwargs): request = kwargs['request'] user = kwargs['user'] print(user) referral = Referral.create( user = user, redirect_to = reverse("Home:afterlogin") ) profile = Profile.objects.create(user= user, … -
Django ORM make a relation with tables depending on eah other (circular reference)
Firstly sorry if this question has already been made somewhere (I really couldn't find nothing after 1 hour of research). How can I make a relation with tables depending in each other with Django ORM? e.g. The users belong to a shop and one of those users is the shop boss. Relation Image -
How to fix "abort" issue in Django?
I am doing a project in Django. I have installed python 3.7.5 and Django 1.11. When I try to run the command python manage.py migrate I am getting [1] abort python manage.py migrate The same thing is happening for python manage.py runserver I have been brainstorming for the last 2 days on how to fix this issue but no luck. Can someone help me out here in fixing this issue? -
How to render links in a template for database filtering in django
I am using the "keyone" column in the database to filter entries. So far in the code i have written i am successfully able to render template with "keyone = 2" values. what should i write in a new template file, and how should i modify existing views.py so that when the template file renders it contains a list of links , each link for each value of "keyone" , when i click on the link say "keyone = 2", the selected entries should get rendered in home.html models.py # app/models.py from django.db import models from django.urls import reverse # new class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] keyone = models.IntegerField(default = '777') def get_absolute_url(self): # new return reverse('post_detail', args=[str(self.id)]) views.py def HomePageView(request): key2select = Post.objects.filter(keyone=2) return render(request, 'home.html', { 'key2select': key2select, }) home.html <ul> {% for post in key2select %} <li>{{ post.keyone }}&nbsp &nbsp{{ post.text }}</li> {% endfor %} </ul> -
Add Cart to Order
I want to make a website with Python-Django, in my case i want to add Item in Cart to Order information. Order model contain User information and OrderItem model contain the Item refer to Order information. and after that i want to clear the Cart model.py class Order(models.Model): full_name = models.CharField(max_length=50) address = models.CharField(max_length=50) city = models.CharField(max_length=15) state = models.CharField(max_length=15) postcode = models.CharField(max_length=10) phone = models.CharField(max_length=15) email = models.EmailField() class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='item', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=0) quantity = models.PositiveIntegerField(default=1) admin.py from .models import Member, Product, Image, Category, Order, OrderItem class OrderItemInline(admin.TabularInline): model = OrderItem raw_id_fields = ['product'] class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'full_name', 'address', 'city', 'state', 'postcode', 'phone', 'email'] inlines = [OrderItemInline] admin.site.register(Order, OrderAdmin) form.py class OrderCreateForm(forms.Form): full_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) address = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) city = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) state = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) postcode = forms.CharField(widget=forms.NumberInput(attrs={'class':'form-control'}), required=True) phone = forms.CharField(widget=forms.NumberInput(attrs={'class':'form-control'}), required=True) email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'})) views.py from .models import Member, Product, Image, User, OrderItem from .forms import * def checkout(request): cart_items = request.session # Create an empty cart object if it does not exist yet if not cart_items.has_key("cart"): cart_items["cart"] = {} item_ids = cart_items["cart"].keys() products = Product.objects.filter(pk__in=item_ids) cart_total = 0 for item in products: cart_item = … -
No module named 'future'
I'm not good at English, so I'm sorry if you couldn't ask questions well in English. I'm having trouble with deploying Django apps on Heroku. I ran git push heroku master.The result is as follows Enumerating objects: 1020, done. Counting objects: 100% (1020/1020), done. Delta compression using up to 8 threads Compressing objects: 100% (1002/1002), done. Writing objects: 100% (1020/1020), 3.24 MiB | 164.00 KiB/s, done. Total 1020 (delta 92), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.7.5 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting ansicolors==1.1.8 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/53/18/a56e2fe47b259bb52201093a3a9d4a32014f9d85071ad07e9d60600890ca/ansicolors-1.1.8-py2.py3-none-any.whl remote: Collecting cachetools==3.1.1 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 2)) remote: Downloading https://files.pythonhosted.org/packages/2f/a6/30b0a0bef12283e83e58c1d6e7b5aabc7acfc4110df81a4471655d33e704/cachetools-3.1.1-py2.py3-none-any.whl remote: Collecting certifi==2019.9.11 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 3)) remote: Downloading https://files.pythonhosted.org/packages/18/b0/8146a4f8dd402f60744fa380bc73ca47303cccf8b9190fd16a827281eac2/certifi-2019.9.11-py2.py3-none-any.whl (154kB) remote: Collecting chardet==3.0.4 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 4)) remote: Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB) remote: Collecting cycler==0.10.0 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 5)) remote: Downloading https://files.pythonhosted.org/packages/f7/d2/e07d3ebb2bd7af696440ce7e754c59dd546ffe1bbe732c8ab68b9c834e61/cycler-0.10.0-py2.py3-none-any.whl remote: Collecting decorator==4.4.1 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 6)) remote: Downloading https://files.pythonhosted.org/packages/8f/b7/f329cfdc75f3d28d12c65980e4469e2fa373f1953f5df6e370e84ea2e875/decorator-4.4.1-py2.py3-none-any.whl remote: Collecting dj-database-url==0.5.0 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 7)) remote: Downloading https://files.pythonhosted.org/packages/d4/a6/4b8578c1848690d0c307c7c0596af2077536c9ef2a04d42b00fabaa7e49d/dj_database_url-0.5.0-py2.py3-none-any.whl remote: Collecting Django==2.2.7 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 8)) remote: Downloading https://files.pythonhosted.org/packages/a0/36/463632a2e9161a7e713488d719a280e8cb0c7e3a66ed32a32e801891caae/Django-2.2.7-py3-none-any.whl (7.5MB) remote: Collecting django-heroku==0.3.1 … -
Unable to run docker with django cookiecutter
I created a project using django cookiecutter. And when I run docker-compose -f local.yml up, "Waiting for PostgreSQL to become available ..." Continues to come out. Starting apasn_postgres_1 ... done Starting apasn_django_1 ... done Attaching to apasn_postgres_1, apasn_django_1 postgres_1 | 2019-11-24 09:33:36.516 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2019-11-24 09:33:36.516 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_1 | 2019-11-24 09:33:36.520 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2019-11-24 09:33:36.536 UTC [22] LOG: database system was interrupted; last known up at 2019-11-24 09:30:25 UTC postgres_1 | 2019-11-24 09:33:36.724 UTC [22] LOG: database system was not properly shut down; automatic recovery in progress postgres_1 | 2019-11-24 09:33:36.726 UTC [22] LOG: redo starts at 0/1651070 postgres_1 | 2019-11-24 09:33:36.726 UTC [22] LOG: invalid record length at 0/1651150: wanted 24, got 0 postgres_1 | 2019-11-24 09:33:36.726 UTC [22] LOG: redo done at 0/1651118 postgres_1 | 2019-11-24 09:33:36.739 UTC [1] LOG: database system is ready to accept connections django_1 | Waiting for PostgreSQL to become available... django_1 | Waiting for PostgreSQL to become available... django_1 | Waiting for PostgreSQL to become available... "Waiting for PostgreSQL to become available ..." is repeated. What … -
Deploy django project in own PC using only Apache not Wamp
I am new python developer. I build a web api service using django. I can run the project using pycharm. Now, i want to run the project using Apache. I do not want to use wamp. I searched but everywhere but there is no suitable source. Everyone suggest to do that using wamp server. But i want to use only apache using mod_wsgi. How can i do that ? -
Sorting A Drop Down Menu in Django With Hard-Coded Choices
I have a few drop down menus that are hard-coded into my model. For example: CITIZENSHIP_CHOICES = { (u'Canada', u'Canada'), (u'USA', u'USA'), (u'United Kingdom', u'United Kingdom'), (u'None', u"None of the above"), } COUNTRY_CHOICES = { ('USA', 'USA'),('Canada', 'Canada'),('Israel', 'Israel'),('UK', 'UK'),('Afghanistan', 'Afghanistan'),('Albania', 'Albania'),('Algeria', 'Algeria'),('Andorra', 'Andorra'),('Angola', 'Angola'),('Antigua and Barbuda', 'Antigua and Barbuda'),('Argentina', 'Argentina'),('Armenia', 'Armenia'),('Australia', 'Australia'),('Austria', 'Austria'),('Azerbaijan', 'Azerbaijan'),('Bahamas', 'Bahamas'),('Bahrain', 'Bahrain'),('Bangladesh', 'Bangladesh'),('Barbados', 'Barbados'),('Belarus', 'Belarus'),('Belgium', 'Belgium'),('Belize', 'Belize'),('Benin', 'Benin'),('Bermuda', 'Bermuda'),('Bhutan', 'Bhutan'),('Bolivia', 'Bolivia'),... } SERVICE_LENGTH_CHOICES = { (6, "6"), (12, "12"), (18, "18"), (21, "21"), (24, "24"), (28, "28"), (30, "30"), (32, "32"), (32, "36"), (42, "42") } All of my fields are in the same model in models.py. Each one of the drop down fields looks like this: citizenship = models.CharField(max_length=100, choices=CITIZENSHIP_CHOICES, null=True, blank=True) For some reason though, in my form, the drop downs are in a strange order. I'd like it either to be in the order I entered it in models.py or to order it alphabetically/numerically. 321 Everything I've found online discusses foreign keys, but I'm not using any foreign keys. Any help is much appreciated. -
How to connect MSSQL Server 2008 with Django
I try to connect my local SQL Serer 2008 with Django, when i try to run the django server then shown this error my connection string is- DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 11 for SQL Server', }, } } -
name 'get_object_or_404' is not defined
I am following this tutorial: https://tutorial-extensions.djangogirls.org/en/homework_create_more_models/ Which i am adding onto a simple blog I made so i can add comments Me error: name 'get_object_or_404' is not defined From this method in views.py def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) # post = Post if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'add_comment_to_post.html', {'form': form}) As you see the #hashed out line. This allows me to get to the comment view but then then I get the error that Cannot assign "<class 'blog.models.Post'>": "Comment.post" must be a "Post" instance. That makes sense but wanted to point that out. I assume this is a database issue? my models.py: from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): comment = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') def __str__(self): return self.comment class Meta: ordering = ['created_on'] Everything in … -
Materialize css adds ::after to input labels and does not display them
Screenshot of the form and inspect page I'm making forms with django for user input. I added materialize css styles. However, the latest removes labels from several inputs in the form as on screenshot. When i disable materialize css, labels display normally. As i've seen, materialize css adds "::after" to some labels. I've tried specifying labels directly in django, however it didn't help. Whan can i do to display them? Django template: {% load static %} {% block content %} <div class="container"> <form method="post"> <h3>Add a new appointment</h3> {% csrf_token %} {% for field in form %} {{ field.label_tag }} {{ field }} {% endfor %} <div class="right-align total"> <button type="submit" class="waves-effect waves-light btn green submit">Submit</button> </div> </form> </div> <script> $(document).ready(function() { $('select').material_select(); }); </script> {% endblock content %} in layout.html i specify <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> -
Alternative to apt-get install packages on pythonanywhere?
I'm trying to deploy a django project to pythonanywhere. I'm using this package in my project: https://github.com/algoo/preview-generator In order for preview-generator to work it has the following requirements: apt-get install zlib1g-dev libjpeg-dev python3-pythonmagick inkscape xvfb poppler-utils libfile-mimeinfo-perl qpdf libimage-exiftool-perl ufraw-batch ffmpeg Is there any way for me to install these required packages on the pythonanywhere server? I read that the best you can do is make a request to the pythonanywhere team to have the packages added in future versions. If this is still the case can anyone recommend a host that allows you to install these kinds of modules? -
operator does not exist: character varying + character varying
I changed the db from sqlite to postgresql for production for my website and I'm getting this error. It didn't get this error when i was working locally with sqlite. ProgrammingError at /boards/1/companies/1/ operator does not exist: character varying + character varying LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Request Method: GET Request URL: http://www.flythecoop.io/boards/1/companies/1/ Django Version: 2.2.6 Exception Type: ProgrammingError Exception Value: operator does not exist: character varying + character varying LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Exception Location: /home/reviews/venv/lib/python3.8/site-packages/django/db/backends/utils.py in _execute, line 84 Python Executable: /home/reviews/venv/bin/python3.8 Python Version: 3.8.0 Python Path: ['/home/reviews/venv/bin', '/home/reviews/reviews', '/home/reviews/venv/lib/python38.zip', '/home/reviews/venv/lib/python3.8', '/home/reviews/venv/lib/python3.8/lib-dynload', '/usr/lib/python3.8', '/home/reviews/venv/lib/python3.8/site-packages'] Server time: Sun, 24 Nov 2019 05:52:27 +0000 Error during template rendering In template /home/reviews/reviews/templates/baseb.html, error at line 0 operator does not exist: character varying + character varying LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Looking at the error, it said something about the snippet … -
Django return response without go through views.py
I'm from php, Laravel. I just start learn python and Django In Laravel, route can return response without go through controller '/home', function(){ return 'hello world'; } I'm wondering can Django do this too? without go through views.py? Something like below urlpatterns = [ path('home/', function(): return 'hello world'; ), ] -
How do I share post data with friends in django?
My views.py is : def home_view(request): """Display all the post of friends and own posts on the dashboard""" if request.user.is_authenticated: context = { 'posts': Posts.objects.filter(author=request.user).order_by('-date_posted'), 'media': MEDIA_URL, } return render(request, 'blog/home.html', context) else: return render(request, 'users/login.html') Thanking you in advance, -
Django "settings are not configured" error and cannot define environment variable DJANGO_SETTINGS_MODULE
This error is easy to reproduce. Read many StackOverflow posts and tried multiple methods but did not work. Created new directory named testproject pipenv install django Started new project named test with the django start project script pipenv shell django-admin runserver Error: "django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Typed this in ubuntu as suggested in the official django docs: export DJANGO_SETTINGS_MODULE=test.settings django-admin runserver Got a giant line of error followed by ModuleNotFoundError: No module named 'test'. However, if i do django-admin runserver --pythonpath=. --settings="test.settings" the server successfully ran. I know I can just use python manage.py to start the server but my project uses Django cache framework and when I try to access the cache the same settings are not configured error is thrown. Trying to understand what is going on, any help would be greatly appreciated. -
Rest Password using django rest framework
How can i reset user password (in case user forgot password) using django rest framework and send the reset password email to user -
Got AttributeError when attempting to get a value for field `user_type_data` on serializer `CustomUserSerializerWithToken`
views.py class CustomUserCreateView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = CustomUserSerializerWithToken(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class UserAdditionalDataModel(models.Model): ACCOUNT_CHOICE = [ ('1', "Employee"), ('2', "Employer"), ] user_type = models.OneToOneField(User, on_delete=models.CASCADE) account_type = models.CharField(choices=ACCOUNT_CHOICE, max_length=255) resume = models.FileField(upload_to='resume/%y/%m/%d/', blank=True, null=True) website = models.URLField(max_length=255, blank=True, null=True) def __str__(self): return self.user_type.mobile serializers.py class CustomUserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) user_type_data = UserAdditionalDataSerializer(many=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): user_type_data = validated_data.pop('user_type_data') password = validated_data.pop('password', None) user_data = self.Meta.model(**validated_data) if password is not None: user_data.set_password(password) user_data.save() for user_type_data in user_type_data: UserAdditionalDataModel.objects.create(user_type=user_data, **user_type_data) return user_data class Meta: model = User fields = ('token', 'mobile', 'password', 'first_name', 'last_name', 'email', 'user_type_data') I am following this tutorial Nested Serializers and I couldn't able to find what's wrong going on here.... when ever I call Post request on this it shows me this error... AttributeError at /core/custom_users/new/ Got AttributeError when attempting to get a value for field `user_type_data` on serializer `CustomUserSerializerWithToken`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no … -
Django: How to mark an option in form from forms.py as selected
Here's my forms.py: from django import forms from users.models import EnglishInterest, UserPlans class CLSelectionForm(forms.Form): plan_choices = UserPlans().get_plan_choices_active() englishInterest_choices = EnglishInterest().get_english_interest_active() useremail = forms.EmailField(widget=forms.HiddenInput(attrs={ 'type': 'email'})) coupon = forms.CharField(widget=forms.HiddenInput(attrs={ 'type': 'email'})) plans = forms.CharField(label='Plan Choice', widget=forms.Select(choices=plan_choices, attrs={'id': 'plan_choice', 'class': 'fs-anim-lower fs-select-box', 'name': 'plan_choice'})) englishInterest = forms.CharField( label='English Interest', widget=forms.Select(choices=englishInterest_choices, attrs={'id': 'english_choice', 'class': 'fs-anim-lower fs-select-box', 'name': 'english_choice'})) submitButton = forms.CharField(widget=forms.TextInput( attrs={'type': 'submit', 'name': 'submit', 'id': 'fs-submit-button', 'class': 'fs-submit', 'value': 'Submit'})) class Meta: fields = ['useremail', 'coupon', 'plans', 'englishInterest'] How would I go about rendering the plans and englishInterest form elements, with options that include a selected attribute? -
Django - AJAX POST to API not working but no errors
I am trying to post data to my Django Rest Framework API, I have a GET request which works. The POST request does not work and the error function of the AJAX call is fired. I cant seem to see why it wont work, perhaps my CSRF or CORS headers are incorrect? main.js $(function () { var $items = $('#items'); var $description = $('#description'); var $price = $('#price'); $.ajax({ type: 'GET', url: '/api', success: function(items) { console.log(items) $.each(items,function(i, item){ $items.append('<li> '+ item.pk +', '+ item.Description +', '+ item.Price +'</li>'); }); }, error: function() { alert('Error Loading Items'); } }); $('#add-item').on('click', function() { var order = { description: $description.val(), price: $price.val(), }; $.ajax({ type: 'POST', csrfmiddlewaretoken: "{{ csrf_token }}", url: '127.0.0.1:8000/api/', data: order, success: function(newItem) { $items.append('<li> '+ newItem.Description +', '+ newItem.Price +'</li>'); }, error: function() { console.log(order) } }); }); }); models.py class Item(models.Model): Description = models.CharField(max_length=20) Price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.Description Serializers Views.py class ItemListAPIView(generics.ListCreateAPIView): lookup_field = 'pk' queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = (AllowAny,) -
Getting error when I am trying to fetch my main url patterns
I am a beginner in Django I have created a Django project in that I have included two more application when I did add urls.py file in both Applications both are working well but when I am fetching my main admin URL it is giving an error Page not found (404) Request Method: GET URL: http://127.0.0.1:8000/ the URLconf defined in mac.urls, Django tried these URL patterns, in this order: admin/ shop/ blog/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. when I am fetching this URL in http://127.0.0.1:8000/ i am getting an error it is working for http://127.0.0.1:8000/shop/ here is my main urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')), path('blog/', include('blog.urls')), ] Please suggest me I would appreciate every response in StackOverflow -
AttributeError 'RegisterDetailView' object has no attribute 'get_object'
I'm attempting to submit a PATCH for an existing record via curl. I want to change my Boolean field from true to false. The primary key is not the default id, but a CharField defined in my models.py I did this hoping to make the url path easier to manipulate; /api/register/serial number vs id number. models.py from django.db import models class Register(models.Model): system_type = models.CharField(max_length=255) serial_number = models.CharField(max_length=255, unique=True, primary_key=True) mac_address = models.CharField(max_length=17, unique=True) ip_address = models.CharField(max_length=15) request = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.serial_number views.py class RegisterDetailView(APIView): serializer_class = serializers.RegisterSerializer def get(self, pk): return Register.objects.get(pk=pk) def patch(self, request, pk): registermodel_object = self.get_object(pk) serializer = serializers.RegisterSerializer(registermodel_object, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) urls.py from django.urls import path, include, re_path from register import views urlpatterns = [ re_path(r'^register/(?P<pk>\w+)/$', views.RegisterDetailView.as_view()), ] curl command curl -d "system_type=switch&serial_number=SAL1834ZDSY&ip_address=f8c2.8887.d480&mac_address=172.16.24.11&request=false" -X PATCH http://192.168.1.100/api/register/SAL1834ZDSY/ When I run my curl command using patch I get this error: AttributeError at /api/register/SAL1834ZDSY/ 'RegisterDetailView' object has no attribute 'get_object' Request Method: PATCH Request URL: http://192.168.1.100/api/register/SAL1834ZDSY/ Django Version: 2.2.6 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8 Python Path: ['.', '', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/opt/django/lib64/python3.6/site-packages', '/opt/django/lib/python3.6/site-packages'] Server time: Sun, 24 Nov 2019 … -
how to check if token was expired in models?
I am trying to expire tokens from forgot password requests, but token from PasswordReset becomes NULL after the user updates their password, however, I was thinking on some kind of solution, but I want to expire the token usage after 1 minute or max 5 minutes to meet security requirements, but I also got created_at . how can I set up an is_expire function to invalid the token? if self.token == None: return False do_expire models.py class PasswordReset(models.Model): email = models.ForeignKey(User, on_delete=models.CASCADE) token = models.CharField(max_length=100, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True)