Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unit-test for custom backends authenticate function locks database
Unit-test for custom django backend's authenticate function is locking the test db I have a unit-test that tests the authenticate function of a custom backend that I have written in my django application. The test itself runs fine. However come cleanup time, django complains that there are active users connected to the test db django.db.utils.OperationalError: database "test_db" is being accessed by other users Following is a complete stack trace: Destroying test database for alias 'default'... Traceback (most recent call last): File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.OperationalError: database "test_dms_db" is being accessed by other users DETAIL: There is 1 other session using the database. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/uname/.vscode/extensions/ms-python.python-2019.6.24221/pythonFiles/ptvsd_launcher.py", line 43, in main(ptvsdArgs) File "/Users/uname/.vscode/extensions/ms-python.python-2019.6.24221/pythonFiles/lib/python/ptvsd/main.py", line 434, in main run() File "/Users/uname/.vscode/extensions/ms-python.python-2019.6.24221/pythonFiles/lib/python/ptvsd/main.py", line 312, in run_file runpy.run_path(target, run_name='main') File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/uname/Projects/python/data_mgmt_soln/manage.py", line 15, in execute_from_command_line(sys.argv) File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/core/management/base.py", line 316, … -
Column does not exist when altering model schema
So i have a model EpicData: class MiddlewareEpicData(models.Model): total_story_points = models.IntegerField() completed_story_points = models.IntegerField() code_review_story_points = models.IntegerField() incomplete_story_points = models.IntegerField(null=True) completion_percentage = models.IntegerField(null=True) code_review_percentage = models.IntegerField(null=True) Now i wanted to add a primary key called key so i alter this like so class MiddlewareEpicData(models.Model): total_story_points = models.IntegerField() completed_story_points = models.IntegerField() code_review_story_points = models.IntegerField() incomplete_story_points = models.IntegerField(null=True) completion_percentage = models.IntegerField(null=True) code_review_percentage = models.IntegerField(null=True) key = models.TextField(primary_key = True, default = "None") I add the default so when i migrate for the first time it will go through with no hitch. The problem is that now when i try to save a value to key it says that the column does not exist for some reason. For this particular migration i am also changing the name of another model so it deletes and adds a new one for that specific one, and i had to use python manage.py migrate --fake without really knowing what it does and it will go through. Here is the migration file: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('kpi', '0006_auto_20190723_1520'), ] operations = [ migrations.CreateModel( name='ComponentMap', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('key', models.TextField()), ('component', models.TextField()), ('type', models.TextField()), ], options={ 'db_table': 'component_bug', }, ), … -
Django error admin.E033: username is not an attribute of users.CustomUser. Why is my custom user admin not working?
I am creating a custom user model in Django. I have defined a custom user model (users.CustomUser) which subclasses AbstractBaseUser. I have created a custom user manager (users.CustomUserManager) which subclasses BaseUserManager and works properly. I have also created a custom user admin which subclasses UserAdmin since my CustomUser model does not have a username field (it uses 'email' instead). As far as I can tell, I have coded everything properly, but when I run 'python manage.py makemigrations' I get an error message: <class 'users.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'users.CustomUser'. I'm stuck here. I have already tried the following: (1) Defined username field to be email in my custom user model class (2) Tried setting username to None in my custom user model class and custom user admin (3) Created custom user registration and change forms and registered them with my custom user admin # models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from phonenumber_field.modelfields import PhoneNumberField from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): username = None firstname = models.CharField(max_length = 60) lastname = models.CharField(max_length = 60) email = models.EmailField(max_length = 240, unique=True) phone = PhoneNumberField(null=True, blank=True) company … -
Django ModelForm: Edit / replace file in FileField in clean
I'm working on a View where users can upload a csv file . However past experience has taught us that the column-names of these user uploaded .csv files often contain extra whitespace, uppercase letters or minor spelling mistakes that cause the rest of the code to trip up (For example: [Username, E-mail, lastname'] instead of ['username', 'email', 'lastname']) These files are uploading using a ModelForm where they are attached to the FileField of the StudentImport model. I've come up with a solution where I'll use the clean_import_file method to check the headers and, if they don't match the expected headers, edit them. That part of the code is working fine, however I am running into trouble at the final step: overriding the original (flawed) file with the new edited file. class StudentImportForm(forms.ModelForm): class Meta: model = models.StudentImport fields = ['import_file'] def save(self, commit=True): obj = super(StudentImportForm, self).save(commit=False) obj.created_by = self.created_by obj.file_type = self.file_type if commit: obj.save() return obj def clean_import_file(self): file = self.cleaned_data['import_file'] df = pd.read_csv( pd.compat.StringIO(file.read()) ) file.seek(0) if list(df.columns) != EXPECTED_COLUMNS: og_columns = list(df.columns.copy()) # Try minor fixes and see if this is enough df.columns = [x.lower() for x in df.columns] df.columns = [x.strip() for x in df.columns] … -
how to count the number of downloads of a file with django
I would like to count the number of file downloads that I put at the disposal of my user, but I can not. My site is in some ways an application library that I design, and that I can share. I use that for Django 2, so I tried to use a middleware, but without finding what he had to do. I can count the number of pages displayed, so I told myself that I could only filter the page of the download, but I realize that it starts without changing pages. Here are the models used : `` `python class Program (models.Model): name = models.CharField(max_length = 100, default = "Nom du Programme") description = models.TextField(default = "Ceci est la description d'un programme") created_at = models.DateTimeField (auto_now = False, auto_now_add=True) updated_at = models.DateTimeField (auto_now = True, auto_now_add=False) image = models.ImageField (upload_to = 'images', null=True) download_file = models.FileField (upload_to = 'executables', null=True) slug = models.SlugField (default="programme_{}".format(id)) youtube_code = models.TextField(null=True) stat_ref = models.OneToOneField('Stat', on_delete = models.CASCADE, null=True) operating_system_ref = models.OneToOneField('OperatingSystem', on_delete = models.CASCADE, null=True) def __str__(self): return self.name ` `` Thanks for help ! -
Django model not saving for some reason, may have to do with concurrency
I am using django-channels (which uses websocket). The function below is run every time a user joins a pregame room. the intended behavior is: the person who created the room is saved as game.creator (no problem with this), and the person who enters after is saved as game.opponent. Much of the time, game.opponent is not saved. Does anyone know why? Thanks in advance @channel_session_user_from_http def ws_connect_pregame(message): message.reply_channel.send({"accept": True}) split_message = message['path'].strip('/').split('/') print(split_message) label = split_message[1] gamelabel = split_message[1] gamepk = gamelabel.split('-')[1] game = Game.objects.get(pk=gamepk) user = message.user if not game.creator: game.creator = user if game.creator and game.creator != user: game.opponent = user game.is_full = True game.save() Group('game-' + gamelabel).add(message.reply_channel) message.channel_session['gamelabel'] = gamelabel -
How to find all the points within a certain radius using google maps api
I have a list of locations in my database stored as lng and lat. The django views is returning the longitude and latitude and latitude of the user location.I would like to return all the locations in the database within 10km of a users location. What would be the best way to do this? def feed(request): latitude = request.session['lat'] longitude = request.session['lng'] radius = 20000 radius = float(radius) / 1000.0 # Distance radius convert m to km lat = float(latitude) # Central point latitude lng = float(longitude) # Central point longitude return render(request,'main/feed.html') -
PostgreSQL tables appear empty in Django
I restored PostgreSQL on pythonanywhere from sql-formatted pg-dump made on my macbook. My tables appear healthy in PostgreSQL, but they appear empty in Django. I suspect I have two schemas or two databases, and the one Django is looking at is empty. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb2', 'USER': 'super', 'PASSWORD': 'bigsecretR4', 'HOST': 'magula6-1249.postgres.pythonanywhere-services.com', 'PORT': '11249', 'OPTIONS': { 'connect_timeout': 60, } } } postgres=# select count(*) from public.cw_city5; count ------- 615 >>> from cw.models import * >>> qs=City5.objects.all() >>> len(qs) 0 -
CORS problem with Django, mising 'Access-Control-Allow-Headers'
I'm having a problem with CORS and Django where, when I try to POST a JSON from my app, I get no response but got an error: Cross-origin request blocked: Same Origin Policy prevents reading of remote resource at http://localhost:8000/converter2/. (Reason: 'access-control-allow-headers' symbol missing in 'Access-Control-Allow-Headers' CORS header during CORS pre-connection). Also, when I try to connect my Django server logs this: "OPTIONS /converter2/ HTTP/1.1" 200 0. Okay, I'm not receiving 'Access-Control-Allow-Headers' from the server. From all I have read this needs to be solved in server side. So I tried to install django-cors-headers and configure it like the following: # settings.py INSTALLED_APPS = [ ... 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True Sadly nothing changed. So I tried change the CORS_ORIGIN_ALLOW_ALL to False and add my app origin to CORS_ORIGIN_WHITELIST, just like this: CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000' ] Again, nothing changed. I tried now to force the headers with the server response, like suggested in this answer: ... response = HttpResponse(status=201) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type" return response Still nothing, I don't know what else I can try. I would appreciate new suggestions, thank you. Ionic v4, port 8100 Django v2.2.4, port 8000 … -
Is there a way to make a Google Place Photos API request without exposing the API Key?
I'm making a web-app where I need to make a request to the Google Places API, this is all good but I also need to make a request to the Places Photo API to display the images of the stuff I find using the places API. To do this, you need to make a request like this: https://maps.googleapis.com/maps/api/place/photo?parameters Where one of mandatory parameters is your API Key. I'm using Django and I'm passing a dictionary that has all the info I need to display. However, in the frontend you can see the API Key in the URL of the image. Is there any way I can avoid that? Thank you so much! -
Retrieving Data Faster Using Django from a Large Database
I have a large database table of more than a million records and django is taking really long time to retrieve the data. When I had less records the data was retrieved fast. I am using the get() method to retrieve the data from the database. I did try the filter() method but when I did that then it gave me entire table rather than filtering on the given condition. Currently I retrieve the data using the code shown below: context['variables'] = variable.objects.get(id=self.kwargs['pk']) I know why it is slow, because its trying to go through all the records and get the records whose id matched. But I was wondering if there was a way I could restrict the search to last 100 records or if there is something I am not doing correctly with the filter() function. Any help would be appretiated. -
Django Dev Server Processing The Same Ajax Request Inconsistently
I'm submitting a POST using ajax clientside. It works fine whenever all the requests are valid. However, when I send a POST request to an invalid URL, and then follow it up with another POST request, regardless of whether it's valid, Django processes the request in a completely different manner. Before changing some code it was actually causing the server to crash. Heres what happens in the Django server stdout when I send two invalid requests in a row: Not Found: /profile/add_favorite [01/Aug/2019 15:42:25] "POST /profile/add_favorite HTTP/1.1" 404 4132 Not Found: /profile/add_favorite [01/Aug/2019 15:42:30] "title=Video+TitlePOST /profile/add_favorite HTTP/1.1" 404 4178 The second request looks ill-formatted, and it's of a different format than the previous request. The request was sent using basic Ajax: var conf = { type: 'POST', url: url, data: {title: "Video Title"}, headers: {'X-CSRFToken': csrftoken}, } $.ajax(conf) And in the dev tools I checked that the requests were the same: That's just the headers but the data is also the same. Anyways, the exact same code was used for both request. This only happens when I send a request to an invalid URL and then send another request after it, and if I reload the page after sending an … -
How to fix duplicate key value violates unique constraint?
I have customized my user model.I have added many other fields in the user model.When I try to add a user by clicking the button "Add User" on the admin panel of Django .The following error occurs. IntegrityError at /admin/accounts/user/add/ duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=() already exists. I am using django2.2 and currently I am learning complex things in django.I have customized my user model .When I try to add a user by clicking this "Add user" in the admin panel of django this error occurs. IntegrityError at /admin/accounts/user/add/ duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=() already exists. Request Method: POST Request URL: http://127.0.0.1:8000/admin/accounts/user/add/ Django Version: 2.2 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=() already exists. Exception Location: C:\Program Files\Anaconda\envs\DjangoEnv\lib\site-packages\django\db\backends\utils.py in _execute, line 84 Python Executable: C:\Program Files\Anaconda\envs\DjangoEnv\python.exe Python Version: 3.7.3 Python Path: ['E:\\Project\\ProductHuntSite', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv\\python37.zip', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv\\DLLs', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv\\lib', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv', 'C:\\Users\\khana\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv\\lib\\site-packages'] Server time: Thu, 1 Aug 2019 22:11:22 +0600 This is my code. class UserManager(BaseUserManager): def create_user(self, username, email, firstname, lastname, profile_photo,mobile_phone_number, password=None, is_staff=False, is_active=True, is_admin=False, is_moderator=False): if not email: raise ValueError("User must have an Email") if not username: raise … -
How to import utils into Django Templates
I'm trying to import a module into my app's settings.py, but am facing the following error: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'templatetags.common_utils': No module named 'templatetags'. My file structure looks like this: app |- assets |- templatetags |-__init__.py |-utils.py |- settings.py And in my settings.py, my TEMPLATES array looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'libraries': { 'common_utils': 'templatetags.common_utils', }, }, }, ] I don't see why Django is failing to find templatetags in 'libraries': { 'common_utils': 'templatetags.common_utils', }, Any help would be much appreciated ! -
Saving a model in a separate thread
In my simple webapp I have a model called Document. When the document is created it is empty. The user can then request to generate it, which means that its content is filled with data. Since this generating step can take some time, it is an asynchronous request: the server starts a thread to generate the document, the user obtains a quick response saying that the generation process started, and after some time the generation is over and the database is updated. This is the code that describes the model: import time from threading import Thread from django.db import models STATE_EMPTY = 0 STATE_GENERATING = 1 STATE_READY = 2 class Document(models.Model): text = models.TextField(blank=True, null=True) state = models.IntegerField(default=STATE_EMPTY, choices=( (STATE_EMPTY, 'empty'), (STATE_GENERATING, 'generating'), (STATE_READY, 'ready'), )) def generate(self): def generator(): time.sleep(5) self.state = STATUS_READY self.text = 'This is the content of the document' self.state = STATE_GENERATING self.save() t = Thread(target=generator, name='GeneratorThread') t.start() As you can see, the generate function changes the state, saves the document and spawns a thread. The thread works for a while (well,... sleeps for a while), then changes and state and the content. This is the corresponding test: def test_document_can_be_generated_asynchronously(self): doc = Document() doc.save() self.assertEqual(STATE_EMPTY, doc.state) … -
'Post' object has no attribute 'comments'?
I'm a creating a basic blog webapp using django. The app starts without an error but when I click on drafts an error come up with AttributeError at /drafts 'Post' object has no attribute 'comments' I've tried by putting comments = models.Manager() but then another error comes up saying Manager isn't accessible via post instances my models.py class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.PROTECT) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) # objects = models.Manager() # comments = models.Manager() def publish(self): self.published_date = timezone.now self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('blogapp:post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title my drafts view look something like class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blogapp/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('create_date') I'm using 'comments' variable in another html and views file. And the same error arise with 'objects' while executing the line Post.objects.filter(published_date__isnull=True).order_by('create_date') in my views.py file -
Skipping over value when inserting data in Django ORM to avoid duplicate error
My table has a composite key using "unique together" like so class ComponentMap(models.Model): key = models.TextField() component = models.TextField() class Meta: unique_together = [['key', 'component']] db_table = 'component_map' as you can see this is connected to my postgres table "component_map" Now this Table is to help figure out if a key has multiple components tied to it. Since there are thousands of different keys, Whenever someone searches for a key, it will grab all the data from a seperate API and then store it into my database to ensure the data will be there. The problem I am having is sometimes whenever someone searches for a specific key that is already in the database to see its components it will give an error duplicate key value violates unique constraint. Usually in Django models it will just update the row if there is a duplicate key, but the unique together seems to break that functionality. What i have tried is this: def insert_data(self, data): values = list((key, name, component_list ) for item in data['issues']) for bug in values: for x in bug[0]: if ComponentMap.objects.filter(key = x): continue for x in bug[2]: c = ComponentMap(key=bug[0], component=x ) c.save() So I thought i … -
Overriding LogoutView.get
I'm trying to override LogoutView.get, to delete an extra cookie. This is my approach: class SignOutView(LogoutView): def get(self, request, *args, **kwargs): """Override get() to delete extra cookie that was set on login.""" res = super().get(request, *args, **kwargs) res.delete_cookie(settings.SESSION_API_KEY_COOKIE_NAME) return res This does not work, the code doesn't seem to be called at all. I don't understand why, when I override a different method, e.g. dispatch, it works as expected. According to http://ccbv.co.uk/ and my understanding of how class based views handle requests, I think I should be able to override LogoutView.get. I'm using Django 1.11.18, but I don't think that matters here. Is there anything obvious that I'm missing? Thanks a lot in advance! -
How to do Django's form client side validation using JavaScript when server side validation already done
I have done Django's form validation at the server-side. Is there any need for client-side validation? If I want to do client-side validation using JavaScript, without writing duplicate validation code at the client-side, can I get Django's server-side validation code at the client-side using JavaScript? So, I can avoid server round-trips and reload time. -
Django “./manage.py bower install
I'm following the instructions from the A calendaring app for Django. setup readme here. I've installed django-bower (v5.1.0) via $ pip install -r requirements.txt (django-bower==5.1.0 is in my requirements.txt). Now I'm trying to run $ ./manage.py bower install but i the commande give me some error he didne found the manage.py the project is : https://github.com/llazzaro/django-scheduler and the error is : ./manage.py : Le terme «./manage.py» n'est pas reconnu comme nom d'applet de commande, fonction, fichier de script ou programme exécutable. Vérifiez l'orthographe du nom, ou si un chemin d'accès existe, vérifiez que le chemin d'accès est correct et réessayez. Au caractère Ligne:1 : 1 + ./manage.py bower geler + ~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (./manage.py:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Efficient way of joining two query sets without foreign key
I know django doesn't allow joining without a foreign key relation and I can't specify a foreign key because there are entries in one table that are not in the other (populated using pyspark). I need an efficient way to query the following: Let's say I have the following tables: Company | Product | Total # Users | Total # Unique Users and Company | Product | # Licenses | # Estimated Users I would like to join such that I can display a table like this on the frontend Company View Product|Total # Users|Total # Unique Users|#Licenses|# Estimated Users| P1 | Num | Num | Num | Num | P2 | Num | Num | Num | Num | Currently loop through each product and perform a query (way too slow and inefficient) to populate a dictionary of lists Way too inefficient -
DRF: Serializing data from external network request
I'm using Django Rest Framework and making external network request which data isn't needed in models but pure serializers. I make an external request to get some data from a server which returns JSON. Here is a quick snipped of it. { "request": [ { "packages": { "gold": [ { "name": "Gold Package 1", "value": "Gold1" }, { "name": "Gold Package 2", "value": "Gold2" } ], "bronze": [ { "name": "Bronze package 1", "value": "Bronze1" }, { "name": "Bronze Package 2", "value": "Bronze2" } ] } ] } After getting this request, I want to return data within this format. How can this be achieved? "response": [{ "details": { "legacy_packages": [{ "name": "Gold Package 1", }, { "name": "Gold Package 2", } ] } }, -
How to connect one django model to many other models?
I'm trying to develop a property management system. I've created the bedroom and bathroom models. In each bedroom and bathroom I need to add lighting, climatization and entertainment models. I've created those models but I'm not sure if I should create another model like "Lighting_Bedroom" and use the ForeignKeys pointing to both models, or if there's another way to do this. // Bedroom Model class Bedroom(models.Model): type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50) bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30) image = models.ImageField(null=True) ensuite = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE) // Bathroom Model class Bathroom(models.Model): sink = models.CharField(db_column='Sink', choices=SINK_BATHROOM_CHOICES, max_length=50) shower = models.CharField(db_column='Shower', choices=SHOWER_BATHROOM_CHOICES, max_length=50) tower_rail = models.CharField(db_column='Tower_Rail', choices=TOWER_RAIL_BATHROOM_CHOICES, max_length=50) image = models.ImageField(null=True) toilet = models.BooleanField(default=False) bidet = models.BooleanField(default=False) bath = models.BooleanField(default=False) extractor_fan = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE) // Properties class Lighting(models.Model): type = models.CharField(db_column='Type', choices=LIGHTING_TYPE_CHOICES, max_length=30) bulb_type = models.CharField(db_column='Bulb_Type', max_length=30) class Climatization(models.Model): type = models.CharField(db_column='Type', choices=CLIMATIZATION_TYPE_CHOICES, max_length=30) use = models.CharField(db_column='Use', choices=CLIMATIZATION_USE_CHOICES, max_length=30) brand = models.CharField(db_column='Brand', max_length=30) model = models.CharField(db_column='Model', max_length=50) remote_control = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. So far I didn't … -
Django: Product matching query does not exist
I have a django-shop project. I add 'add to cart' function and it works. But when I try to get quantity added to cart I get an error 'Product matching query does not exist'. Here is the view that works. def add_to_cart_view(request): cart = getting_or_creating_cart(request) product_slug = request.POST.get('product_slug') product = Product.objects.get(slug=product_slug) new_item, _ = CartItem.objects.get_or_create(product=product, item_cost=product.price, all_items_cost=product.price) if new_item not in cart.items.all(): cart.items.add(new_item) cart.save() new_cart_total = 0.00 for item in cart.items.all(): new_cart_total += float(item.all_items_cost) cart.cart_total_cost = new_cart_total cart.save() return JsonResponse({ 'cart_total': cart.items.count() }) And this view after upgrading and it's not working def add_to_cart_view(request): cart = getting_or_creating_cart(request) product_slug = request.POST.get('product_slug') product = Product.objects.get(slug=product_slug) if request.method == "POST": form = CartAddProductForm(request.POST or None) if form.is_valid(): quantity = form.cleaned_data['quantity'] new_item = CartItem.objects.create(product=product, item_cost=product.price, all_items_cost=product.price, quantity=quantity) if new_item not in cart.items.all(): cart.items.add(new_item) cart.save() print("It's done!") else: print('Not valid') else: print('Not POST') new_cart_total = 0.00 for item in cart.items.all(): new_cart_total += float(item.all_items_cost) cart.cart_total_cost = new_cart_total cart.save() return JsonResponse({ 'cart_total': cart.items.count(), }) Here is the traceback Environment: Request Method: POST Request URL: http://localhost:8000/add_to_cart/ Traceback: File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view … -
I want to upload a pdf format file into xampp mysql database table using django
I want to upload a pdf file along with other details of a person using django, Xampp Mysql. For example, along with person's name, address, phone number, I want to upload a pdf file which contains some content related to the person. I've used the below code in modules.py to store person's name, address and contact number. Now, after contact number, I also want to upload a pdf file to the same table using django, mysql. modules.py class person_upload(models.Model): name=models.CharField(max_length=100) address=models.CharField(max_length=100) phone=models.CharField(max_length=100) views.py def w_upload(request): name=request.POST['pname'] address=request.POST['paddress'] phone=request.POST['pphone'] insert=person_upload(name=name, address=address, phone=phone) insert.save()