Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting an error when running server in Django
when executing py manage.py runserver command I get the error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\users\galen\mysite\mysite\urls.py", line 20, in <module> path('polls/', include('polls.urls')), File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\conf.py", … -
Converting data types for python and django
I have two main variables, week_order_overall_total which is a custom python money data type using this (https://github.com/mirumee/prices) and then the actual integer references below (5, 200, 15 etc). When I try I do a calculation with the two using payout = week_order_total_card - hm_fees, I get an error message: '>=' not supported between instances of 'Money' and 'int' I imagine this is because there are two different data types being used. I have tried resolving it using int(week_order_overall_total) but that doesn't work. CODE: if trial_status =="yes": if admin_value <=5: hm_fees=5 else: hm_fees=admin_value elif early_customer =="yes" and week_order_overall_total >=1 and week_order_overall_total <= 200: hm_fees=15 elif week_order_overall_total == 0: hm_fees=0 elif week_order_overall_total >= 1 and week_order_overall_total <= 200: hm_fees=20 elif week_order_overall_total >= 201 and week_order_overall_total <= 400: hm_fees=35 else: hm_fees=55 payout = week_order_total_card - hm_fees Any help is appreciated. -
Redirect back to previous page after login in django-allauth
There is a button in blog detail view that asks user to login to comment, but after login user is redirected to home page because in settings.py I declared: LOGIN_REDIRECT_URL = "projects:home" I searched and I found this could be a solution: <a href="{% url 'account_login' %}?next={{request.path}}">Please login to reply</a> but this even didn't work. Thank You -
How to make Django template engine recognize an expression from an injected string
I am injecting meta/title tags dynamically for each page by using a yaml file full of html tags. HTML {% if meta_tags %} {% for tag in meta_tags %} {{ tag|safe }} {% endfor %} YAML trending_bonds: - '<title>Trending Searches for {% now "Y-m-d" %}</title>' The view just loads the yaml into a dict of strings and passes it along to template in that meta_tags variable. I need that {% now %} expression to be run and show the current date but it keeps getting inserted as a string just like shown above. Any ideas? -
Django html template how to display variable inside variable?
i have templater which contains.Driver, Car and campaign model and i have template base model wherere all model and body, text and another field contains and i added in body {driver.fleet} but when i try to see html template its not shwoing value of fleet its just shows {driver.fleet} like this. <section class="table_driver" style="margin: 0 auto; max-width: 760px;"> <div class="somehtinff_fix"> {{template.container_en|safe}} #this is fiels </div> </section> conainer_en text is like this Our tips for you: (General tip) To give you more peace of mind and a safer driving, next morning, you should go and inflate you tires to the currect pressure. Why?(link) {driver.fleet} #this should through that driver fleet name (Specific tip) We also noticed that you have the tendecy to drive in a lower gear even on a straight, this forces your engine to overspeed, use more fuel and overheat. Try to drive on a higher gear on a straight even if you driving slow. Try driving in a 4th or 5th gear, 6th might be to hight but you can try, less noise, smoother driving and less 5 to 10% fuel consumption. Trip(Link this is the code where template file exist ctx = { "driver": self.driver, # `here … -
How to save user input in database from django form
I hava created a small project in django where i have created a form and with 3 fields now i want if user type his name , email and invite message then it should save in databse. i am unable to save the data in database. form.py from datetime import datetime from bootstrap_datepicker_plus import DatePickerInput from django.contrib.admin.widgets import AdminDateWidget from bootstrap_datepicker_plus import DateTimePickerInput from bootstrap_datepicker_plus import TimePickerInput # from .models import check class Email_app(forms.Form): Name = forms.CharField() Email = forms.EmailField() Invite = forms.CharField() start_date = forms.DateField(label="Start_Date", widget=DatePickerInput()) start_time = forms.DateField(label="Start_Time", widget=TimePickerInput()) end_date = forms.DateField(label="End_Date", widget=DatePickerInput()) end_time = forms.DateField(label="End_Time", widget=TimePickerInput()) def __str__(self): return self.Name Form > enter image description here below is the view.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import formatdate # from email import encoders from email.encoders import encode_base64 import os,datetime COMMASPACE = ', ' # from django.shortcuts import render # Create your views here. from django.shortcuts import render from operators.settings import EMAIL_HOST_USER from . import forms from django.core.mail import send_mail # Create your views here. #DataFlair #Send Email def email_app(request): sub = forms.Email_app() if request.method == 'POST': sub = forms.Email_app(request.POST) subject = 'Welcome to Email Event' message = … -
Passing Data Through AJAX Call Causes Failure
I am building a really simple AJAX call using Python/Django. I've never had issues with it before, but now I keep on getting a Not Found error if I ever put actual data in the AJAX call. Works fine if I place no data. I must be making a very obvious mistake that I just can't see. In my code below, if I comment out the #test value it will work fine, so I know all the URLs are working correctly. It's just if I add any real data it fails (#product_id_notes is just filler, does not refer to an actual ID). Can anyone help bail me out here? This has been driving my crazy for the last several hours. My error: Not Found: /admin/ajax/order_analysis My code: <button id = 'test1234' >Submit</button> <input id = "submit-order-analysis-url" type = 'hidden' value = ' {% url 'admin:order_analysis' %} '> <div id = "test" value = "123">This is a test</div> <script> $('#test1234').click(function(){ var url = $('#submit-order-analysis-url').val(); var data = {'test':$('#test').val(), 'product_id':$('#product_id_notes').val() } $.ajax({url: url, data: data}) .done(function(data){ //do nothing }) .fail(function(){ //do nothing console.log("Something went wrong") }); }) </script> -
How to aggregate time for each employee in bi-weekly pay schedule in Django
How to add up time_work for each employee up to 15th of each month? class TimeLog(models.Model): employee = models.IntegerField(null=True, blank=True, related_name='employee id') start_date = models.DateTimeField (null=True, blank=True) end_date = models.DateTimeField (null=True, blank=True) time_worked = models.DurationField(null=True, blank=True) -
Python requests login to django
hey im trying to login into the django page at https://extensions.gnome.org/ import requests from bs4 import BeautifulSoup client = requests.Session() client.headers.update({"referer": "https://extensions.gnome.org/accounts/login/"}) data = client.get("https://extensions.gnome.org/accounts/login/") soup = BeautifulSoup(data.text) mtoken = soup.find("input", {"name": "csrfmiddlewaretoken"}) print(mtoken["value"]) csrftoken = client.cookies["csrftoken"] login_data = client.post("https://extensions.gnome.org/accounts/login/", data={ "csrfmiddlewaretoken": csrftoken, "username": "email", "password": "password", "next": "/" }) print(login_data.text) but the response is always invalid csrf token. has someone an idea how to get this working? -
Update Django model instance only if certain condition is met
I'm trying to solve what looked like an easy problem at first to me and probably I'm overthinking it, but I'm unsure where to put the bit of logic required, so any input would be much appreciated. Following situation (example code, not real project) # models.py class Product(models.Model): title = models.CharField() price_in_cents = models.IntegerField() # ... class ProductImage(models.Model): product = models.ForeignKey('Product', null=True, blank=True) image = models.ImageField() user = models.ForeignKey(get_user_model()) # ... So in short I have products and images that show these products. This is part of a DRF project which is consumed by a Vue frontend. The flow is as follows: The client creates new images by posting the image data to /api/productimages/ The API creates the Image instance and returns the data including the created instances PK. The client then posts a list of image ids along with the data to create the product to /api/products/ the api creates the product and should now associate the passed images with the created product. This should only happen if current user == image.user and image.product is not set yet (==Null) Now my question: Where should I put the logic to associate the images with the created product? I see the … -
Django ValidationError when serializing nested object
So I have a serializer like this: class FirstSerializer(serializers.ModelsSerializer) second = SecondSerializer() class Meta: model = First While validating SecondSerializer may raise ValidationError. If it does, in return I get this: { "first": { "second": [ "Error" ] } } How can I make this error not connected with validated field, for example: { "non_field_errors": [ "Error" ] } -
Django whats the .distinct('column_name') for SQLite equivalent?
In my current project, I need to select all distinct elements from my SQLite database and I wanted to use: distinct_ingredients = Ingredients.objects.all().distinct('ingredient') But I learned that this just works for I think PostgreSQL, so my question is what is the equivalent to .distinct(column_name) for an SQLite Database? I tried different things out but the didn't give me the distinct ones. Thanks for your help. -
Currency symbol not displaying correctly on Saleor platform
Please I have some issue with displaying the right currency symbol for Naira in saleor platform. In the documentation, I saw it could be changed by redefining DEFAULT_CURRENCY in settings.py DEFAULT_CURRENCY = os.environ.get("DEFAULT_CURRENCY", "USD") How I approached the issue: Saleor-platform default currency came with USD which displayed $ as the currnecy symbol (e.g $ 1000) Then I changed it to NGN but it displayed NGN as the currency symbol (e.g NGN 1000) instead of ₦1000 And then I tried changing it to EUR and it displayed € as the currency symbol (e.g €1000) Maybe minor countries where not considered while building the platform. Please could there be a way to tweak this? see screenshot of the display below: saleor currency display -
Django: get_or_create not creating object, only reporting error that matching query does not exist
I am making my first django web (mostly for fun -hence the theme, toilet rating app- and learning). But this stopped being fun a day ago. I am trying for user to be able to create and rate the toilets (create/update user's rating). Creation is fine, the rating is where I have all the issues. The current and biggest problem is that line rating, created = Rating.objects.get(user_id=user, toilet_id=toilet) is throwing rating.models.Rating.DoesNotExist: Rating matching query does not exist. Now the snippets: VIEW: @login_required(login_url='login') def rate_toilet_view(request, upk, tpk, *args, **kwargs): toilet = Toilet.objects.get(id=tpk) user = User.objects.get(id=upk) rating, created = Rating.objects.get(user_id=user, toilet_id=toilet) form = RatingForm(instance=rating) if request.method == "POST": form = RatingForm(request.POST, instance=rating) if form.is_valid(): form.save() toilet = Toilet.objects.get(toilet_id = toilet) # SOME COMPUTATIONs HERE toilet.save() return redirect('/') context = {'form': form} return render(request, 'pages/rate_toilet_form.html', context) MODELS: class Rating(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) user_id = models.ManyToManyField(User, through='RatingUser') toilet_id = models.ManyToManyField(Toilet, through='RatingToilet') # FIELDS TO BE RATED HERE class RatingUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.ForeignKey(Rating, on_delete=models.CASCADE) class RatingToilet(models.Model): toilet = models.ForeignKey(Toilet, on_delete=models.CASCADE) rating = models.ForeignKey(Rating, on_delete=models.CASCADE) class Toilet(models.Model): CATEGORY = (#CATEGORIES OF TOILETS HERE#) id = models.IntegerField(primary_key=True, auto_created=True) category = models.CharField(max_length=120, null=False, choices=CATEGORY, default=None) place = models.CharField(max_length=120) # OVERAL VALUES OF RATED … -
URL Keep Adding Backslash Django
I need your help in fixing this issue. urlpatterns = [ path('', views.dashboard, name='dashboard'), path('menu', views.menu, name='menu'), path('close', views.close, name='close'), path('lead', views.lead, name='lead'), path('audience', views.audience, name="audience"), path('audience/<action>', views.audience, name="audience") ] That's my code URLs but I keep getting a backslash at the end of the URL. For instance, if I link to dashboard/menu, I get dashboard/menu/ -
Django 1.11 - Attempting to populate models with fake data using Faker
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() ##fake pop script import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t= Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): #get topic for entry top = add_topic #create fake data fake_url = fakegen.url() fake_Date = fakegen.date() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] # create a fake acess record for taht Webpage acc_rec = AccessRecord.objets.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print('populating script!') populate(20) print('populating complete') Hello, so I am working on a Django course, it is using Django 1.11 as the question mentioned, and while trying to populate my models with fake data using Faker, I am getting some errors coming from the Django packages i believe, below are the command line errors i received, thanks in advanced! enter code here (MyDjangoEnv) D:\Coding Projects\DjangoCourse\first_project>python populate_first_app.py populating script! Traceback (most recent call last): File "populate_first_app.py", line 44, in populate(20) File "populate_first_app.py", line 37, in populate webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", l ine 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", lin e 464, in get_or_create return self.get(**lookup), False File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", lin e 371, in get clone = self.filter(*args, … -
Uncaught TypeError: Cannot set property 'innerHTML' of null Django
I know there are many similarly to this question but I can't find a way. I have a table and when I click edit in row table the modal should show and I want to pass data from table to modal and display some data in modal that comes from my table .When the button click it always error and the modal didn't show.I been using Django.Please see the image below. Below is my current code. Can you help me please? Error accounts.html {% extends 'navigation.html' %} {% block content %} <script> function exampleModal(firstName,lastName){ document.getElementById('firstNameValueId').innerHTML = firstName document.getElementById('secondNameValueId').innerHTML = lastName $("#exampleModal").modal('show'); } </script> <!-- mytable --> <div class="tabs-animation"> <div class="card mb-3"> <div class="card-header-tab card-header"> <div class="card-header-title font-size-lg text-capitalize font-weight-normal"><i class="header-icon lnr-laptop-phone mr-3 text-muted opacity-6"> </i>Accounts Information </div> <div class="btn-actions-pane-right actions-icon-btn"> <div class="btn-group dropdown"> <button type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="btn-icon btn-icon-only btn btn-link"> <i class="pe-7s-menu btn-icon-wrapper"></i> </button> <div tabindex="-1" role="menu" aria-hidden="true" class="dropdown-menu-right rm-pointers dropdown-menu-shadow dropdown-menu-hover-link dropdown-menu"> <h6 tabindex="-1" class="dropdown-header">Header</h6> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-inbox"> </i><span>Menus</span> </button> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-file-empty"> </i><span>Settings</span> </button> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-book"> </i><span>Actions</span> </button> <div tabindex="-1" class="dropdown-divider"></div> <div class="p-3 text-right"> <button class="mr-2 btn-shadow btn-sm btn btn-link">View Details</button> <button class="mr-2 … -
Provision product with strip and dj-stripe
I'm using stripe with DRF and on top of that, I've implemented the library dj-stripe. Everything works so far but I'm not really sure how to provision my product now. I do have access to the subscription and customer object for every user but these objects are quite complicated / big. I can't really do something like if user.subscription -> do this since the subscription could be e. g. deleted, inactive. I also need a more granular solution since I need to apply limits like: if subscription.plan.product === "Entry Plan": # allow user to only create 5 instances I can't really find information on how to do this elegantly and consistently for an entire app. -
How to add a number range of items per page in custom pagination django rest framework
I have created some serialized data using django rest framework. I am in the process of building a custom pagination, since there is a lot of data that is being serialized. I have managed to add the required key, value pair needed in the custom pagination. The page_size is set to 200. So it currently displays like this : { "totalPages": 11, "totalData": 2065, "currentPage": 2, "nextPage": "http://localhost:8000/cluster/37/tasks?page=3", "previousPage": "http://localhost:8000/cluster/37/tasks", "results": [...] } I want to also display additional data in the custom pagination, I want to display the range of the starting data (firstDataNumber) and the final data (lastDataNumber) in the page. For example in page 1 : { "totalPages": 11, "totalData": 2065, "currentPage": 1, "firstDataNumber" : 1, #first data on page "lastDataNumber" : 200, #last data on page ... } same for page 2, which should be : { "totalPages": 11, "totalData": 2065, "currentPage": 2, "firstDataNumber" : 201, #first data on page "lastDataNumber" : 400, #last data on page ... } How do I achieve this insertion of a range of data number in the custom pagination? Thanks. This is my code on custom pagination so far : class LargeResultsSetPagination(PageNumberPagination): page_size = 200 page_size_query_param = 'page_size' max_page_size = … -
Django TextField does not enforce blank=False
I can't get django.db.models.TextField(blank=False) to enforce non-blank. It seems to ignore the constraint and only enforces not-null. Example: import django.core.exception import django.db.models import unittest class Mymodel(django.db.models.Model): id = django.db.models.AutoField(primary_key=True) text = django.db.models.TextField(blank=False) with self.assertRaises(django.core.exception.ValidationError): Mymodel.objects.create() # <--- should raise validation exception The above code creates a new Mymodel instance with the text field set to a blank string, but instead it should raise a ValidationError -
How do you pass data like this (Shown in the question body) as form data in postman for django rest framework api?
Hey guys I have data like this to be passed on to the form-data in postman or insomnia, but the problem is I am getting this error all the time if I use form-data to send. { "product_variation": [ "This field is required." ] } This is the data I am sending. "product_variation": [ { "size-colour": "1", "size_name": "small", "colour_name": "Green", "price": "100", }, { "size-colour": "2", "size_name": "medium", "colour_name": "Blue", "price": "100", } ] Also, I am not able to send images if I try to send the data as raw json data. Can anyone tell me how to properly send this? Thanks -
How to change default empty representative in forms CharField?
I use an unbound form with BooleanField and CharField None are required but when empty, value in database is a representative empty string for Charfield and 0 for BooleanField I would like NULL value instead but don't find how to set this. class CreateForm(forms.Form): def __init__(self, request, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields["field1"] = forms.BooleanField(label = "", required = False, initial=None) self.fields["field2"] = forms.CharField(label = "", required = False, initial=None) -
I created an extra table extra table in one to one relation with User table. how to show phone field in User registration
I am trying to create a simple API to get a user register. I am using the default User table for authentication purpose, created another table called "phone" with one to one relation with User. I am trying to add "phone" field just above the password. (I hope the image attached is visible). ** Serializer.py class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = UserDetailsModel fields = ('phone', 'user') class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=68, min_length=6, write_only=True) class Meta: model = User fields = ('username','first_name', 'last_name','email','password') read_only_fields = ('id',) ** models.py<< ** class UserDetailsModel(models.Model): phone = models.IntegerField() balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) user = models.OneToOneField(get_user_model(),primary_key='email' , on_delete=models.CASCADE) def __str__(self): return str(self.user) ** views.py ** 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 return Response(user_data,status=status.HTTP_201_CREATED) class DetailsRegisterView(generics.GenericAPIView): serializer_class = UserRegisterSerializer 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 return Response(user_data,status=status.HTTP_201_CREATED) ** urls ** urlpatterns = [ path('',RegisterView.as_view()), path('details', DetailsRegisterView.as_view()) ] ** -
Post.get in django and html form method
what will be form method in html if i use post.get[] . I tried post and get but it gave me 'method' object is not subscriptable error . -
Docker build getting errors after I tried to install pip install -r requirements.txt file
This is the error I get after I installed RUN pip install -r requirements.txt RROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 ➜ django-docker pip install psycopg2 Defaulting to user installation because normal site-packages is not writeable Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) ERROR: Command errored out with exit status 1: command: /usr/bin/python3.6 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-7xuxd9cm/psycopg2/setup.py'"'"'; file='"'"'/tmp/pip-install-7xuxd9cm/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-uon18vv4 cwd: /tmp/pip-install-7xuxd9cm/psycopg2/ Complete output (23 lines): running egg_info creating /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info writing /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.