Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where are CachingManager, CachingMixin, cached_method in Djnago 2.0?
I am upgrading a django project of version 1.4 to djnago version 2.0.there in models.py it has an import path from caching.base import CachingManager, CachingMixin, cached_method. But i dont know where to import above in django 2.0 version? -
Filter on nested serializer and Foreing Key Django/Rest Framework
Following are my model classes class ProductClass(models.Model): name = models.CharField('Name') class Product(models.Model): title = models.CharField('Product title') description = models.TextField('Description') product_class = models.ForeignKey(ProductClass, null=True, blank=True, related_name='products') class ProductPriceRepository(models.Model): product = models.ForeignKey(Product, related_name='price_repo') #: For a given entry we add maximum price of 99,999.99 unit. price = models.DecimalField('price of product', max_digits=7, decimal_places=2) is_default = models.BooleanField() This is how I have defined my view class ProductClassList(APIView): def get(self, request, format=None): product_classes = ProductClass.objects.filter(products__price_repo__is_default=True) serializer = ProductClassSerializer(product_classes, many=True) return Response(serializer.data) I have defined serializes as follow class ProductPriceRepositorySerializer(serializers.ModelSerializer): class Meta: model = ProductPriceRepository fields = ('price',) class ProductSerializer(serializers.ModelSerializer): price = SerializerMethodField() class Meta: model = Product fields = ('title', 'description', 'price') def get_price(self, obj): for price in obj.price_repo.all(): if price.is_default: serializer = ProductPriceRepositorySerializer(price) return serializer.data class ProductClassSerializer(serializers.ModelSerializer): products = SerializerMethodField() class Meta: model = ProductClass fields = ('name', 'products') def get_products(self, obj): for product in obj.products.all(): for price in product.price_repo.all(): if price.is_default: serializer = ProductSerializer(product) return serializer.data Output looks like [ { "name": "Product Class Test One", "products": { "title": "Test Product One", "description": "", "price": { "price": "100.00" } } }, { "name": "Product Class Test Two", "products": { "title": "Test Product Two", "description": "", "price": { "price": "30.00" } } } ] … -
Optimal SQL query for annotating materialized path descendents
Im currently using the django-treebeard library for its materialized path representation and helper functions, and running into an issue when trying to annotate the total number of descendents for each node in the tree. Namely, its slow. As you can see from the glaring inner query, i need to perform a count for each row of the outer to check for the children that share its path. My current solution is just staggering the queries by depth, so that the entire tree isn't ever queried, but that still leads to decent, however still noticeably slow performance on the front end as each time a node's children need to be displayed a query is required. I was curious if anybody else had run into this niche problem, or if anybody had any ideas as to how this could be further optimized. -- This query of 1000 takes around 45 seconds to complete... unusable at the use case of 40,000 SELECT "hierarchynode"."orphan", "hierarchynode"."path", "hierarchynode"."depth", "hierarchynode"."numchild", (SELECT count(*) FROM "hierarchynode" U0 WHERE U0."path"::text LIKE REPLACE(REPLACE(REPLACE(("hierarchynode"."path"), '\', '\\'), '%', '\%'), '_', '\_') || '%') AS "numdescendent" FROM "hierarchynode" WHERE ("hierarchynode"."broken_chain" = False AND "hierarchynode"."orphan" = False) LIMIT 1000 -
Django create new instances of a different model using the submitted form data of a model
I have a Topic model which has a ManyToManyField to the Tag model. Similarly to stack overflow where you can submit new tags at the time of asking a question. I want to be able to create new tags when you create a topic. A hacky solution from the top of my head. Class TopicCreateView(CreateView): # blah blah.... def form_valid(self, form): tags = self.request.POST.getlist(tags) for tag in tags: if not Tag.object.filter(tag_string__iexact=tag): try: new_tag = Tag.objects.create(tag_string=tag) except IntegrityError: # stuff I'm new to Django and web frameworks in general, but this seems really hacky to me (if it even works). Given what I've read so far regarding FormSets and such, is there not a better way to achieve this? -
Microsoft Visual C++ 14.0 is required. error when downloading a python package
When im trying to download a python package 'pip install django-compressor' in my django project, its giving this error. PS C:\Users\HP\Desktop\acornaccounting> pip install django-compressor Collecting django-compressor Using cached https://files.pythonhosted.org/packages/02/7b/deb4605f95bcefb9760ff130533553230a1c25f4d383ed0735b075d71b29/django_compressor-2.2-py2.py3-none-any.whl Requirement already satisfied: django-appconf>=1.0 in c:\users\hp\appdata\local\programs\python\python36\lib\site-packages (from django-compressor) (1.0.2) Collecting rjsmin==1.0.12 (from django-compressor) Using cached https://files.pythonhosted.org/packages/10/9c/2c45f57d43258b05bf33cf8f6c8161ea5abf8b4776a5c59d12646727cd98/rjsmin-1.0.12.tar.gz Collecting rcssmin==1.0.6 (from django-compressor) Using cached https://files.pythonhosted.org/packages/e2/5f/852be8aa80d1c24de9b030cdb6532bc7e7a1c8461554f6edbe14335ba890/rcssmin-1.0.6.tar.gz Installing collected packages: rjsmin, rcssmin, django-compressor Running setup.py install for rjsmin ... error Complete output from command c:\users\hp\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\HP\\AppData\\Local\\Temp\\pip-install-i9yu03ey\\rjsmin\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\HP\AppData\Local\Temp\pip-record-sb4anuu2\install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build\lib.win-amd64-3.6 copying .\rjsmin.py -> build\lib.win-amd64-3.6 running build_ext building '_rjsmin' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools -
Installing GeoDjango on a windows Computer error at: Modify Windows environment
I am trying to install GeoDjango in my Django Project I am using Python 3.6 and Django 1.11 . I started used the link install GeoDjango on Windows I did everything perfectly. I already had Python, PostgreSQL, PostGIS, psycopg2 installed from before I installed OSGeo4W All these done perfectly. However as soon as I reached Modify Windows environment reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t I get a error in my cmd.exe that says C:\Users\Samir>reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t ERROR: Invalid syntax. Type "REG ADD /?" for usage. I tried doing what the error message said but I got the below error C:\Users\Samir>REG ADD /?"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t ERROR: Invalid key name. Type "REG ADD /?" for usage. How can I fix this error -
Django:Unable to save form data to database
I have a multi-step form/wizard which I am using to register users. However, I am unable to save the data. I have given various print commands throughout the code to debug what is happening during the runtime. The print statements shows that everything seems to be working. However, I am gettig empty objects created in Database with Null values. Below is the code snippet: views.py from django.shortcuts import render, render_to_response from .models import User, Password, PersonalDetails, CCDetails, RoundUpDetails, construct_instance #from .models import User from .forms import PostForm from formtools.wizard.views import SessionWizardView from django.core.mail import send_mail class ContactWizard(SessionWizardView): template_name = 'Done.html' def done(self, form_list, form_dict, **kwargs): form_data = process_form_data(form_list) return render('home.html', {form_data: 'form_data'}) def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] data = [User, Password, PersonalDetails, CCDetails, RoundUpDetails] for i, x in enumerate(form_data): print("value of x: ", x) inst = data[i] newObject = inst() print ("BnewObject", newObject) for k, v in x.items(): print("value of key: ", k) print("value of value: ", v) newObject.k = v print("newObject.k:", newObject.k) newObject.save() print("AnewObject", newObject) The output: value of x: {'email': 'as@gmail.com'} BnewObject User object () value of key: email value of value: as@gmail.com newObject.k: as@gmail.com AnewObject User object () value of x: {'user': 'po', … -
I can not install django channels in a bunch the docker-compose
I faced with very enteresting error. I began to consider the django-chanels and can not start the chanels on docker-compose + gunicorn + nginx. My app is work fine, but channels is not run when start a server. For example: I is added 'channels' to INSTALLED_APPS and start my containers. When start server i must get error, since is missing this str: ASGI_APPLICATION = 'myapp.routing.application'. But error is missing. If I run server without docker, only with command: python manage.py runserver, then I get this error. I think on nginx or gunicorn.conf, but I do not understand how they can influence this. If need, this command is start my server: gunicorn --config app/gunicorn_config.py myapp.wsgi:application. Any idea? -
Having issue in parsing dictionary in template
views.py-- def SubCategoryList(request): subcategory_form = SubcategoryForm(request.POST or None) context ={ 'form' : subcategory_form } #print(SubcategoryForm.POST.Category_id) if subcategory_form.is_valid(): #print("Hi") print(subcategory_form.cleaned_data['Category_id']) qs = SubCategory.objects.filter(cat_id=subcategory_form.cleaned_data['Category_id']) data = {} for qss in qs: data[qss.subcategory_id] = qss.subcategory_name for k,v in data.items(): print(data[k]) print(data) return render(request,"Subcategory/cat_sub_list.html",data) return render(request,"Subcategory/sub_list.html",context) cat_sub_list.html-- {% for key,v in data.items %} {{ v }} {% endfor %} sub_list.html <form method='POST'> {% csrf_token%} {{form}} <button type="submit" class="btn btn-default">Submit</button> </form> {{form}} has a integer input field. It is redirecting to cat_sub_list.html after inputting value sub_list.html. But not printing value of data(dictionary) after parsing. -
Django media not loading, static files working
I'm trying to run a jango site, static files are working, media is not loaded from the media folder, if the picture in static files is visible. The folder is listed correctly, pycharm gives a fall in the folder setings.py STATIC_ROOT = '/home/static/' STATIC_URL = '/static/' # MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') MEDIA_ROOT = '/home/media/' MEDIA_URL = '/media/' urls.py if settings.DEBUG: import debug_toolbar # Server statics and uploaded media urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Allow error pages to be tested urlpatterns += [ url(r'^403$', handler403), url(r'^404$', handler404), url(r'^500$', handler500), url(r'^__debug__/', include(debug_toolbar.urls)), ] I use django oscar, this can be the cause of the problem? -
Django: Admin panel not showing all entries when using custom ModelAdmin class
I have a simple Django model class Tourney(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, verbose_name=_('Location'), related_name='tourneys') date = models.DateField(_('Date')) ... When I use this ModelAdmin class class TourneyAdmin(admin.ModelAdmin): list_display = ('id', 'date',) the admin panel shows every entry in the database. But when I include the location field like class TourneyAdmin(admin.ModelAdmin): list_display = ('id', 'date', 'location',) some entries are not shown in the list. On the bottom of the page the number of entries (x Tourneys) is still shown correctly. Any idea why that is happening? Here is the Location class: class Location(models.Model): name = models.CharField(_('Name'), unique=True, max_length=50) -
Save multiple models in a single post - Django rest frameweok
I have 4 models class User(AbstractEmailUser): first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) class Event(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) date = models.DateField() class EventLocation(models.Model): event = models.ForeignKey(Event) ubigeo = ArrayField(models.CharField(max_length=200), blank=True) class EventStaff(models.Model): recycler = models.ForeignKey(User) event = models.ForeignKey(Event) When I want to register an event and be able to assign users to this same publication at the time of creation, assign users or do not assign them. I have already created a nested serialier that in the documentation is well explained so that the event is saved and at the same time it is saved in the ubigeo field of the EventLocation table (code of the district of the place): Class EventLocationSerializer(serializers.ModelSerializer): class Meta: model = EventLocation fields = ('id', 'ubigeo') class EventSerializer(serializers.ModelSerializer): event_location = EventLocationSerializer(required=True, write_only=True) def to_representation(self, instance): representation = super(EventSerializer, self).to_representation(instance) event_location = EventLocation.objects.filter(event=instance.id) if event_location: representation['event_location'] = event_location.values('ubigeo')[0] return representation class Meta: model = Event fields = ('id', 'date', 'name', 'address', 'schedule', 'event_location') def create(self, validated_data): location_data = validated_data.pop('event_location') event = Event.objects.create(**validated_data) EventLocation.objects.create(event=event, **location_data) return event def create(self, validated_data): location_data = validated_data.pop('eventlocation') event = Event.objects.create(**validated_data) EventLocation.objects.create(event=event, **location_data) and it works correctly, but how would you add the users you want to assign … -
Running a Django Web Server Using Java
I want to execute the following command prompt command in Java code: python manage.py runserver How can I do it? -
How to merge changes in your django app once you've already deployed it on the server using heroku?
If possible please tell the terminal command also. i've created a new git branch to do so. -
django channels ASGI_APPLICATION
i have an old project using django 1.x where i haven't set the ASGI_APPLICATION and the project works normally, now i'm trying to get back to learning channels, and i am using 2.x but it doesn't work without me setting ASGI_APPLICATION is this a channels 2 thing ? or is it a problem with my project ? -
Django - Pass value from pre_save to post_save methods on model
I've got a Django model like so... class Example(models.Model): title = models.CharField(...) ... I'm trying to compare two values - the title field before the user changes it, and the title after. I don't want to save both values in the database at one time (only need one title field), so I'd like to use pre_save and post_save methods to do this. Is it possible to get the title before the save, then hold this value to be passed into the post_save method? The pre_save and post_save methods look like so... @receiver(pre_save, sender=Example, uid='...') def compare_title_changes(sender, instance, **kwargs): # get the current title name here x = instance.title @receiver(post_save, sender=Example, uid='...') def compare_title_changes(sender, instance, **kwargs): # get the new title name here and compare the difference x = instance.title # <- new title if x == old_title_name: # <- this is currently undefined, but should be retrieved from the pre_save method somehow ...do some logic here... Any ideas would be greatly appreciated! -
While creating I just want user which is logged in, only able to edit/update his info and not others. And can only see the details of other employee
So Only current user can edit his info and see others info but can't edit/update others.While creating I just want user which is logged in, only able to edit/update his info and not others. And can only see the details of other employee. Here is my models.py from django.db import models # Create your models here. GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('NA','Undisclosed') ) class Employee(models.Model): first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) username = models.CharField(max_length=15,unique=True) email = models.EmailField(max_length=50,unique=True) mobile = models.IntegerField(default = 0) nationality = models.CharField(max_length=20) address = models.CharField(max_length=100) city = models.CharField(max_length=30) state = models.CharField(max_length=20) gender = models.CharField(choices=GENDER_CHOICES, default="NA",max_length=100) def __str__(self): return self.username Here is my views.py class EmployeeCreateView(CreateView): form_class = EmployeeForm template_name = 'portal/employee_form.html' success_url = reverse_lazy('emp_list') class EmployeeListView(ListView): model= Employee class EmployeeDetailView(DetailView): model = Employee class EmployeeUpdateView(UpdateView): model = Employee fields = ('first_name','middle_name','last_name','username','email', 'mobile','nationality','address','city','state','gender',) success_url = reverse_lazy('emp_list') class EmployeeDeleteView(DeleteView): model = Employee success_url = reverse_lazy('emp_list') -
manage.py runserver opens up pycharm instead of running server
I'm pretty new to coding in general and could really use someones help with this! I installed django via CMD on my WIN 10 computer and when I run the server it works. D:\Python\Python37-32\website>manage.py runserver 8080 Performing system checks... System check identified no issues (0 silenced). August 04, 2018 - 15:32:59 Django version 2.1, using settings 'website.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CTRL-BREAK. However... I than downloaded Pycharm Community edition on my computer and instead of the server starting, it just opens up the pycharm ide and the server doesnt run. The interpreter looks fine as well. D:\Python\Python37-32\website>manage.py runserver 8080 D:\Python\Python37-32\website> -
Attempt to redirect to homepage: Django always redirects to accounts/login when path(r'') is defined but not when path(r'^$') is defined
I've been having trouble with my project this morning. Here are my settings: My project is called Roomies so in the Roomies subfolder: my Roomies urls.py: My roomies views.py: For some reason, this code returns a Page not found (404) but if I change the first url path: path(r'^$', views.homepage, name='homepage') to: path(r'', views.homepage, name='homepage') or path('', views.homepage, name='homepage') http://127.0.0.1:8000/ automatically redirects to http://127.0.0.1:8000/accounts/login and displays everything properly. I feel like it has to do with my syntax or my lOGIN_EXEMPT_URLS but I can't put a finger on my mistake. Here is my accounts urls.py in case that helps: Thanks in advance for the help! -
ModuleNotFoundError: No module named 'MySQLdb' with django 1.10.5
I am facing this error when calling python manage.py migrate for the first time.I am in windows. Installed mysql, created database, put the database name as well. The django version is 1.10.5 Some of the solutions say that the visual studio developer tools might fix the problem, I installed the visual stdio 2017 developer tools, still The problem is persisting. ModuleNotFoundError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "I:\python projects\Virtual_Environments\todo_project_venv\todo_venv\lib\site-packages\django\core\management\__init__.py", line 367, in execute_ from_command_line utility.execute() File "I:\python projects\Virtual_Environments\todo_project_venv\todo_venv\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "I:\python projects\Virtual_Environments\todo_project_venv\todo_venv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "I:\python projects\Virtual_Environments\todo_project_venv\todo_venv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "I:\python projects\Virtual_Environments\todo_project_venv\todo_venv\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "I:\python projects\Virtual_Environments\todo_project_venv\todo_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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "I:\python projects\Virtual_Environments\todo_project_venv\todo_venv\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "I:\python projects\Virtual_Environments\todo_project_venv\todo_venv\lib\site-packages\django\contrib\auth\base_user.py", line 52, in … -
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module
I am getting the following error when I try and use manage.py after setting up my MySQL database connections in Django 2. Traceback (most recent call last): File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so, 2): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.21.dylib Referenced from: /Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/sheldon/.local/share/virtualenvs/django-server-xw4tZkRJ/lib/python3.7/site-packages/django/db/models/base.py", line 101, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File … -
Default NGINX Page On Everything But Last Server Name
I'm trying to connect my DigitalOcean Droplet to my custom domain. It's a Django website. The server_name will only go to the last thing in the list. So, if I have "server_name www.mydomain.com, mydomain.com" www.mydomain.com won't work (goes to the "Welcome to nginx!" page), but mydomain.com will. If I do the opposite, the opposite happens. What do I do for this? This is basically my "/etc/nginx/sites-available/myproject" as it stands: server { listen 80; server_name 142.93.58.126, mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/myproject; } location / { include proxy_params; proxy_pass http://unix:/root/myproject/myproject.sock; } } The IP doesn't work, but the "mydomain.com" does because it's last. Any idea what might be going on here or how to see? I want to be able to have mydomain.com and www.mydomain.com work. -
Issue with PyCharm Community Edition and Django runserver
I'm pretty new to coding in general and could really use someones help with this! I installed django via CMD on my WIN 10 computer and when I run the server it works. D:\Python\Python37-32\website>manage.py runserver 8080 Performing system checks... System check identified no issues (0 silenced). August 04, 2018 - 15:32:59 Django version 2.1, using settings 'website.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CTRL-BREAK. However... I than downloaded Pycharm Community edition on my computer and instead of the server starting, I kept getting this message in the manage.py file... Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Im not sure whats going on here, I've been searching for an hour or so but can't seem to figure it out. Any help would e greatly appreciated, thank you in advance! -
getting data from html files and saving it to models django
I have created multiple input fields and when i click submit i need that data to be saved into my database through models.py that i created. However I am unable to understand how to redirect that data from html to django. This is my html file <!DOCTYPE html> <head> <meta charset="utf-8" /> <title>Cars</title> <h1> Enter sales data to store</h1> </head> <body> <div> <form method="post"> {% csrf_token %} <label for="billingnumber">Billing Number:</label> <input type="number" id="billingnumber" name="billingnumber"><br/> <label for="customername" >Customer Name :</label> <input type="text" id="customername" name="customername"><br/> <label for="purchasedate">Purchase Date:</label> <input type="date" id="purchasedate" name="purchasedate"><br/> <label for="price">Price:</label> <input type="number" id="price" name="price" ><br/> <label for="carcompany">Car Company:</label> <input type="text" id="carcompany" name="carcompany"><br/> <label for="carmodel">Car Model:</label> <input type="text" id="carmodel" name="carmodel"><br/> <label>Car Serial Number:</label> <input type="number" id="carserial" name="carserial"><br/> <label for="mfgdate">Car Manufacturing Date:</label> <input type="date" id="mfgdate" name="mfgdate"><br/> <label for="shippingdate">Shipping Date:</label> <input type="date" id="shippingdate" name="shippingdate"><br/> <button type="submit" value="submit">Submit</button> </form> </div> <a href="/">Home<a> </body> </html> This is my models.py class cars(models.Model): billingnumber = models.BigIntegerField(primary_key=True) customer = models.TextField() price = models.IntegerField() purchasedata = models.DateTimeField() carcompany = models.TextField() carmodel = models.TextField() carserialnumber = models.BigIntegerField() carmfgdate = models.DateTimeField() shippingdate = models.DateTimeField() These are my url patterns urlpatterns = [ url(r"^$", TemplateView.as_view(template_name="index.html"), name="home"), url(r"^store/$", TemplateView.as_view(template_name="store.html"), name="store"), url(r"^access/$", TemplateView.as_view(template_name="access.html"), name="access"), url(r"^about/$", TemplateView.as_view(template_name="about.html"), name="about"), ] I am unable to … -
django reverse url hitting another url
I have a base URL file that includes all apps URL files, and what I am trying to do is on click of Generate PDF Button, I want to hit an APIView / view-function passing a variable along as parameter via get method without encoding. HTML: <form onsubmit="{% url 'api-product:invoice-pdf-get' %}?R={{ variable }}"> <input type="submit" value="Generate PDF"> </form> Base URL path('api/product/', include(('store.urls', 'store'), namespace='api-product')), path('invoice/', InvoiceUrl.as_view(), name='print-invoice'), App URL: path('invoice-pdf-get/', invoice.InvoiceToPdf.as_view(), name='invoice-pdf-get'), On Click URL Generated: (Which is current, except with parameter) http://localhost:8000/invoice/? Can't understand why am I getting the same URL though when I inspect the HTML I see the URL included there, but without localhost:8000. There are several answers related to reverse URL on StackOverflow, none helped.