Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To stop git accessing my changes made in django project in vscode
I had pushed my django project into github from vscode,later i deactivated my virtual environment,but even after deactivating if i try to make any changes in my project it is asking me to apply local changes to git,how to prevent it?Please Help me To Solve this Issue i deactivated the virtual environment and made changes on my project,but it is still asking me to apply those changes to git.I dont want this changes to be applied to github,how to prevent it? -
JS element returns 'null' when retrieving value from textarea
For my project, I'm submitting a "tweet" form asynchronously, but I'm having trouble retrieving the textarea value to pass into my function and update the UI. The values from the tweet/post are saving to my models (including the tweet) and every other field in (username, user profile picture, tweet image) are displaying properly, but its just the textarea that's causing me problems and not displaying at all. Here is the relevant code for reference. Section of index.html <form id="tweet-form" method="post"> <div class="post-section-row"> <a class="creator" href="{% url 'change_profile' %}"> <img src="{{ user_profile.profile_picture.url }}" class="profile-pic small-post-section" > </a> <!-- Cannot retrieve value from this line --> <textarea id="post-content" name="tweet" placeholder="What's Happening?" oninput="autoExpand(this); checkCharacterCount(this)"></textarea> </div> <!-- To display tweet image preview and delete functionality --> <div id="tweet-picture-preview" style="display: none;"></div> <div class="post-section-row"> <div class="error-message"></div> <div class="tweet-actions"> <label for="picture" title="Upload Picture"> <span class="material-symbols-outlined">photo_library</span> <span class="tooltiptext">Upload Picture</span> <input type="file" id="picture" name="tweet-picture" class="file-input" accept="image/jpeg, image/png, image/gif, image/jpg" onchange="previewTweetImage(event)"> </label> <input type="submit" id="post-button" value="Post"> </div> </div> </form> JS file (code within DOMContentLoaded listener) tweetForm.addEventListener('submit', function(event) { event.preventDefault(); const csrftoken = getCookie('csrftoken'); const formData = new FormData(tweetForm); fetch("/post_tweet/", { method: "POST", body: formData, headers: { 'X-CSRFToken': csrftoken, }, }) .then(response => response.json()) .then(data => { console.log(data.message); // This returns … -
How to serve Files with Django Rest Framework
In my django app I have a "Incidence" model that has several FileField and ImageField. I want to create an endpoint with Django Rest Framework to retrieve the information about an "Incidence" but what I have done so far only retrieves the url of the files. I need to return the files in a format that can be downloaded by the client application like binary data or other suggestion. How can I do it? This is what I have done so far Model Definition: class Incidence(BasicAuditModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) geom = models.PointField(verbose_name=_("Localización"), srid=4326, blank=True, null=True) name = models.CharField(_("Nombre"), max_length=255) incidence_type = models.CharField(_("Tipo incidente"), max_length=50, choices=INCIDENCE_TYPE_CHOICES, default="tipo1") description = models.TextField(_("Descripción"), blank=True, null=True) status = models.CharField(_("Status"), max_length=50, choices=STATUS_CHOICES, default="creado") image1 = models.ImageField(verbose_name=_("Foto 1"), upload_to="incidencia_fotos", null=False, blank=False) image2 = models.ImageField(verbose_name=_("Foto 2"), upload_to="incidencia_fotos", null=False, blank=False) image3 = models.ImageField(verbose_name=_("Foto 3"), upload_to="incidencia_fotos", null=False, blank=False) audio = models.FileField(verbose_name=_("Audio"), upload_to="incidencia_audioa", null=False, blank=False) video = models.FileField(verbose_name=_("Video"), upload_to="incidencia_video", null=False, blank=False) def __str__(self): return self.name class Meta: db_table = 'sini_incidence' managed = True verbose_name = 'Incidencia' verbose_name_plural = 'Incidencias' class BasicAuditModel(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="+", verbose_name=_("Creado por"), null=True, blank=False, on_delete=models.SET_NULL) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="+", verbose_name=_("Modificado por"), null=True, blank=False, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True, verbose_name=_("Fecha creado")) modified = models.DateTimeField(auto_now=True, verbose_name=_("Fecha … -
django connecting to mysql in docker gets "wrong" IP address
I am attempting to connect to a remote mysql db from my dockerized django app. This works as expected: In [2]: pymysql.connect(host='remote-host.com', user='user', password='bogus') Out[2]: OperationalError: (1045, "Access denied for user 'user'@'172.XX.XX.XX' (using password: YES)") In [3]: pymysql.connect(host='remote-host.com', user='user', password='secret') Out[3]: <pymysql.connections.Connection at 0x401ef682b0> But this does not (from within django runserver): File "/usr/local/lib/python3.8/site-packages/pymysql/protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.8/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) django.db.utils.OperationalError: (1045, "Access denied for user 'user'@'192.168.80.4' (using password: YES)") So somehow the shell-based connection is picking up a 172/ IP address for the client (presumably the docker bridge IP - it doesn't correspond to my laptop's en0 IP at any rate), where the exact same code, exact same connection params within runserver causes the mysql server to see the IP of the docker container. Anyone know what's going on, and more importantly how I can prevent it? Attempted: Well, not really much I can do since I don't have access to modify mysql's accepted host list or how it determines the client IP. Expected: The same IP address to be used in both connections. -
Django: Generating a file on page load and deleting it upon exit
Something I would like to do in my Django app is: every time a user views page A, grab information from my database, generate an image based off this and display it to the user. Since I am regenerating an image each time I view the page, I would like it to be unique to each user and deleted when they leave page A to go to any arbitrary page B (and ideally when they simply click x on the browser too, but if not that's okay). So far I can generate the image file and save it just fine. I have tried a few things unsuccessfully and can't figure out how to go forward. Things I have tried: @receiver(request_finished) @receiver(request_finished) def handle_request_finished(sender, **kwargs): ... clean up files here ... My issue with this one is that it happens too quickly and won't load the picture on page A because it will be deleted already. Using a JavaScript function that activates when leaving the page paired with a function in my views.py In template.html: <script> $(window).on('beforeunload', function () { $.ajax({ url: pageLeaveUrl, // links to page_leave function in views.py type: 'GET', async: false // Ensure the request completes before page … -
Can't specify STATICFILES_DIRS correctly in Django
I'm getting the warning: (staticfiles.W004) The directory 'C:/frontend/build' in the STATICFILES_DIRS setting does not exist. It seems like i'm not able to reference my react build folder correctly, all this happened after trying to move django api folders. Here is what my folders look like: enter image description here And here's how my path related setting look like in my settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "frontend/build")], "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", ], }, }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = "static/" # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" STATICFILES_DIRS = [ os.path.join( BASE_DIR, "/frontend/build") ] I've tried debugging my settings.py, it seems like the BASE_DIR is never set correctly, im not able to understand os.path.join -
Django Admin - Add a tabularInline section referred to another class (without foreign key)
I'm developing a Django Admin interface for a sort of ecommerce. I have some database model linked using foreign key. In Django Admin interface, I want to show a TabularInline section inside Customer page to show me all items buyed by a specific customer but I have a classic error about "foreign key" because Customer model and OrderItems model are not directly linked. class Customer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=150) mobile = models.CharField(max_length=20, blank=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] class Meta: verbose_name = "Account" verbose_name_plural = "Accounts" def email_user(self, subject, message): send_mail( subject, message, 'l@1.com', [self.email], fail_silently=False, ) def __str__(self): return self.email class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") full_name = models.CharField(max_length=50) email = models.EmailField(max_length=254, blank=True) address1 = models.CharField(max_length=250) address2 = models.CharField(max_length=250) city = models.CharField(max_length=100) phone = models.CharField(max_length=100) postal_code = models.CharField(max_length=20) country_code = models.CharField(max_length=4, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) total_paid = models.DecimalField(max_digits=5, decimal_places=2) order_key = models.CharField(max_length=200) payment_option = models.CharField(max_length=200, blank=True) billing_status = models.BooleanField(default=False) class Meta: ordering = ("-created",) def __str__(self): return str(self.created) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) product = models.ForeignKey(ToolTable, related_name="order_items", on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, decimal_places=2) … -
Get param on anothe page and edit : Vue-Axios-Django-Python
I would like to retrieve the data passed as a parameter via the route and make one of the modifications, but I can't. This is my Python-Django code # CompanyApi @csrf_exempt def companyApi(request, id=0): if request.method == "GET": companies = Companies.objects.all() # companies = Companies.objects.first() # companies = Companies.objects.order_by("company_id").first() companies_serializer = CompanySerializer(companies, many=True) # companies_serializer = CompanySerializer(companies) return JsonResponse(companies_serializer.data, safe=False) elif request.method == "POST": company_data = JSONParser().parse(request) companies_serializer = CompanySerializer(data=company_data) if companies_serializer.is_valid(): companies_serializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse("Failed to Add", safe=False) elif request.method == "PUT": company_data = JSONParser().parse(request) company = Companies.objects.get(company_id=id) # company = Companies.objects.get(company_id=company_data["company_id"]) companies_serializer = CompanySerializer(company, data=company_data) if companies_serializer.is_valid(): companies_serializer.save() return JsonResponse("Updated Successfully", safe=False) return JsonResponse("Failed to Update") elif request.method == "DELETE": company = Companies.objects.get(company_id=id) company.delete() return JsonResponse("Deleted Successfully", safe=False) This is my code is my CompanyEdit page <script setup> import axios from "axios"; import { computed, ref, onMounted, reactive } from "vue"; import { useRoute } from "vue-router"; import CardBoxModal from "@/components/CardBoxModal_JTO.vue"; import FormField from "@/components/FormField.vue"; import FormControl from "@/components/FormControl.vue"; import BaseButton from "@/components/BaseButton.vue"; import SectionMain from "@/components/SectionMain.vue"; import CardBoxWidget from "@/components/CardBoxWidget.vue"; import CardBox from "@/components/CardBox.vue"; const modalOneActive = ref(false); const form = reactive({ company_id: "", company_name: "", company_email: "", company_phone: "", company_address: "", company_city: "", … -
Django signal when model instance with custom field is deleted?
I've got a custom model field in my Django app: secret = VaultField(max_length=200) This takes the value passed and saves it to HashiCorp Vault and stores the path to it in the database, and retrieves it from Vault when accessing. That's all good, I can use this on many models. But now when I delete an instance of a model it doesn't delete it from Vault. I could add a post delete signal on all models that have the VaultField field, but that seems like a lot of duplicate work. Is there anything to add in the class VaultField(CharField): class? Or maybe a post delete signal just on a field being deleted? -
Django or Javascript/Node: learning times in relation to difficulty?
I've been using Python for years, but always for desktop apps. I know Html, Css and little Javascript, but I've never programmed in backend for websites. I would like to learn Django, but having a look I found it very difficult. Knowing Python well and knowing little about Javascript, does it take less time to learn Django from scratch to carry out projects of medium difficulty, or does it take less time to learn Node.js from scratch with Express? (also considering the time to learn Javascript at least sufficiently) -
Gunicorn not finding module - Django
Im trying to deploy my app to Railway.app website, but it keeps giving this message in deploy logs: ModuleNotFoundError: No module named 'ci_jacaranda' I have done some changes in folder structure and now I cant solve what is wrong with it. Basically I changed the old ci_jacaranda/ folder which contains the settings to configs/. This is my project folder configuration: ci_jacaranda ├───apps │ ├───core //[views and urls] ├───configs (old ci_jacaranda) └───__init__.py └───asgi.py └───settings.py └───urls.py └───wsgi.py ├───static └───templates Inside my settings.py INSTALLED_APPS = [ 'admin_datta.apps.AdminDattaConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.core', 'django_bootstrap5', ] ROOT_URLCONF = 'configs.urls' WSGI_APPLICATION = 'configs.wsgi.application' Inside wsgi.py and asgi.py i changed to configs too import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'configs.settings') application = get_wsgi_application() Manage.py import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'configs.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() My Procfile: web: python manage.py migrate && gunicorn configs.wsgi:application I runs in my windows local machine, but as always: not in the server, the … -
django-python like button
Hi lads I want to add like button to make project. but getting error. Exception Value: Reverse for 'like_recipe' with arguments '('',)' not found. 1 pattern(s) tried: ['add_recipe/like/(?P[0-9]+)/\Z']enter image description here[[enter image description here](https://i.stack.imgur.com/My5IO.png)](https://i.stack.imgur.com/AR7Uy.png) I didn't try anything as I cant understand were i problem -
Enforcing row level permission in Django Models
I am trying to enforce row (object) level permissions in Django, on the model level. All the resources on the web revolve around two possible solutions: Option 1. Passing the request manually to a custom manager with a for_user() method: # manager class EntryManager(models.Manager): def for_user(self, user): return self.get_queryset().filter(owner=user) # model class Entry(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) objects = EntryManager() # usage in views/serializers/forms/admin/... Entry.objects.for_user(request.user) Option 2: Using threading.local() variables to store the request/user in the middleware, and than access them in the model. Examples: https://github.com/benrobster/django-threadlocals https://github.com/Alir3z4/django-crequest https://www.viget.com/articles/multi-tenancy-in-django/ I don't like option 1, because it relies on a developer calling a for_user() method, which can be often forgotten. There are a lot of people on the internet that don't like option 2, because of the usage of threadlocals and also because of a Django philosophy that models should be request-unaware. I am coming from a framework such as Laravel which allows access to the Request and User at all levels, so I am puzzled why this is a no-no in Django. I did take a look at django-guardian as well, but the module seems quite complex, and no easy way to filter out all objects linked to a user. Also … -
How to style grouped checkboxes from CheckboxSelectMultiple in django with crispy_form
Here is my form: class MyForm(forms.ModelForm): foo = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'flat'})) class Meta: model = MyModel exclude = ['bar', 'baz'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choices = ( ('Groupe1', ( (1, 'Item1'), (2, 'Item2'), )), ('Groupe2', ( (1, 'Item1'), (2, 'Item2'), )), ) self.fields["foo"].choices = choices self.helper = FormHelper(self) self.helper.form_id = 'myform_id' self.helper.form_class = 'myform_class' self.helper.form_method = 'GET' self.helper.use_custom_control = True self.helper.label_class = 'font-weight-bold' Once rendered, I would like to change the style of the group labels. But I don't know how to access it. When I inspect my form, I see the structure looks like this: <form> <div class="form-group"> <div class="controls"> <strong>Groupe1</strong> <div class="checkbox"> <label class="" for="id_actes_select_0_0"> <div class="icheckbox_flat-green" style="position: relative;"> <input type="checkbox" name="foo" value="Item1" class="flat" id="id_actes_select_0_0"> </div> Item1 </label> </div> ... </div> </div> </form> Group labels are wrapped in strong tags. I would like to style them in css. How to do it with crispy_form ? -
Subtract two quantities value from two different class model in Django
I am trying to do a subtraction from Add_Purchase model to Received_Payment check how many payment received against selected User PK and check if payment not received 100% remaining payment show in HTML form can you please confirm me any one which function use in views.py file I'll share our model here according to above given question thanks. class Add_Purchase(models.Model): date_of_purcahse = models.DateField() supplier_info = models.ForeignKey(add_supplier, on_delete=models.CASCADE) product_type = models.ForeignKey(Product_Type, on_delete=models.CASCADE) product_item = models.ForeignKey(Product_Item, on_delete=models.CASCADE) product_price = models.CharField(max_length=100) product_qty = models.CharField(max_length=100) bill_num = models.CharField(max_length=100) def __str__(self): return self.supplier_info class Received_Payment(models.Model): monthly_inst = models.DecimalField(max_digits=10, decimal_places=2, null=True) client_name = models.ForeignKey(Add_Buyer, on_delete=models.CASCADE) item_payment_received = models.ForeignKey(Cridet_Sale, on_delete=models.CASCADE) payment_date = models.DateField() slip_number = models.CharField(max_length=50) def __str__(self): return str(self.payment_date) -
Permission denied: mod_wsgi, when using mod_wsgi with apache2 and pyenv
I was trying to deploy django app using mod_wsgi (version=4.9.4), apache2 and pyenv, also created the python virtual-env using pyenv, here is the apache configuration used <VirtualHost *:80> ServerName dev.<domain>.com WSGIDaemonProcess dev.<domain>.com python-home=<path><to><pyenv-virtualenv> python-path=<projectdir> WSGIProcessGroup dev.<domain>.com WSGIApplicationGroup %{GLOBAL} ErrorLog "${APACHE_LOG_DIR}/timesheet_internal.log" CustomLog "${APACHE_LOG_DIR}/timesheet_internal.log" common LogLevel Warn Alias /static /var/www/<projectpath>/static <Directory /var/www/<projectpath>/static> Require all granted </Directory> Alias /.well-known/acme-challenge/ "/var/www/<projectpath>/.well-known/acme-challenge/" <Directory "/var/www/<projectpath>/"> AllowOverride None Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec Require method GET POST DELETE PATCH OPTIONS </Directory> WSGIScriptAlias / /var/www/<path>/wsgi.py <Directory "/var/www/<path>/wsgi.py"> Require all granted </Directory> </VirtualHost> <pyenv-virtualenv>/bin/python manage.py --collectstatic --no-input --clear and <pyenv-virtualenv>/bin/python manage.py migrate --no-input both these commands are executed successfully and the app also worked in my local, but on deploying in ec2(ubuntu 22.04) the application ran into following errors [Mon Jun 12 14:17:51.520596 2023] [wsgi:warn] [pid 1224676:tid 140062563575680] (13)Permission denied: mod_wsgi (pid=1224676): Unable to stat Python home /home/ubuntu/.pyenv/versions/3.11.3/envs/timesheet_env. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/.pyenv/versions/3.11.3/envs/timesheet_env' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir … -
facing Python Package version issues
I am trying to run an old django project which was build on python 3.6. currently I am using venv with python 3.10 & below is my list of dependencies mysqlclient==1.3.13 arrow==0.12.1 gunicorn==19.9.0 pymongo==3.7.1 pytrends==4.4.0 Faker==0.9.1 newsapi-python==0.2.3 progressbar2==3.38.0 newspaper3k==0.2.7 requests==2.17.1 beautifulsoup4==4.6.3 selenium==3.14.0 lxml==4.2.5 pandas==0.23.4 langdetect==1.0.7 pyjwt==1.6.4 msgpack==0.5.6 bpython==0.17.1 xlsxWriter==1.1.1 feedparser==5.2.1 querystring-parser==1.2.3 google_images_download==2.5.0 xlrd==1.2.0 algoliasearch==2.0.4 PyMySQL==0.9.3 fuzzywuzzy==0.17.0 python-levenshtein==0.12.0 firebase-admin==4.3.0 can any one suggest me package version for smooth project run? -
Django rest framework and axios post dont work [closed]
I am trying to make a simple api where a user presses a button and then an axios post adds a new instance. I use django rest framework and react. views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) serializers.py from rest_framework import serializers from .models import * class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' App.js function handleSubmit(e) { axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" axios.post('http://127.0.0.1:8000/post', { headers:{ 'content-type': 'application/json' }, data: { name: 'a', title: 'b', } }).then(res=>{ console.log(res) }).catch(error=>console.log(error)) } return ( <> <button onClick={handleSubmit}>OK</button> </> ); When I press the button I get `POST http://127.0.0.1:8000/post 500 (Internal Server Error) and Error: Request failed with status code 500 at e.exports (createError.js:16:15) at e.exports (settle.js:17:12) at XMLHttpRequest.S (xhr.js:66:7) What should I do? I dont have a problem with CORS. -
Gmail API OAuth 502
I have the following code that works perfectly on my local machine, but on the remote server, it doesn't redirect to Google OAuth and gives me a 502 error. Where could I have made a mistake? SCOPES = [ 'https://mail.google.com/', ] def get_gmail_service(): creds = None config_path = os.path.join(os.path.dirname(__file__), 'config') credentials_path = os.path.join(config_path, 'creds.json') token_path = os.path.join(config_path, 'token.json') if os.path.exists(token_path): creds = Credentials.from_authorized_user_file(token_path, SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( credentials_path, SCOPES) creds = flow.run_local_server(port=0) with open(token_path, 'w') as token: token.write(creds.to_json()) try: service = build('gmail', 'v1', credentials=creds) return service except HttpError as error: print(f'An error occurred: {error}') def get_emails(): service = get_gmail_service() .... I just need to authenticate with OAuth to access my Gmail account and retrieve emails from it. -
How to add extension to Test Database in django?
I'm using TrigramSimilarity in my project. but when i want to test my view in a testcase it seems that the test database doesn't have the extention. how do i add the extention in test database? def test_person_search(self): query = str(self.person.name) url = reverse("persons:person_search") + f"?q={query}" test_data = { "query": query, "results": [ { "name": "TestPerson", "picture": None, "roles": [{"role": "Test", "slug": "test"}], } ], } response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, test_data) Error: django.db.utils.ProgrammingError: function similarity(character varying, unknown) does not exist LINE 1: ...."height_centimeter", "persons_person"."picture", SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. -
Django not migrating CharField with choices properly
I have a model Car with a CharField color, that has the choices of white, black and blue. class Car(models.Model): WHITE = "White" BLACK = "Black" BLUE = "Blue" COLOR_CHOICES = ( (WHITE, "White"), (BLACK, "Black"), (BLUE, "Blue"), ) ... color = models.CharField(max_length=20, choices=COLOR_CHOICES, default=BLUE) I already have created Car objects with a color. Now when I introduce a change to the choices (e.g. change BLUE to RED in all occurences, as well as in the default) and run the migrations, the Car objects of color BLUE that already exist do not get migrated to RED. And that's where the weirdness begins: When I use the django shell to check the objects, they appear as Car.BLUE (the choice that no longer exists). When I inspect the objects in the Django Admin, they appear as Car.WHITE. When I create a new object, it works - it becomes Car.RED automatically (picks up the default). Questions: Are there any specific steps that I missed when migrating choices for the CharField? Why could this weird behavior be happening and how can I safely fix? Do I have to manually (or through a script) fix the data? I expect upon migration all existing Car.BLUE objects … -
How to assign an empty value to an object attribute in Django Admin Interface?
I'm designing an eBay-like website. My project has several models, one of which, namely "Listing", represents all existing products: class Listing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=512) category = models.CharField(max_length=64) image_url = models.URLField() owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created_listings") is_active = models.BooleanField(default=True) winner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="won_listings", null=True) I need the winner attribute to be able to equal an empty value. But when I try to assign it an empty value in Django Admin Interface, I get an error: How can I solve this problem? Thank you in advance! -
how to download uploaded image
After uploading an image through drf, I want to automatically download it when the user clicks on the image. models.py views.py detailblog.html urls.py If i click the file name, it will be downloaded, but the current page, not the uploaded picture, will be saved in html format. How can i solve this problem? i want to download uploaded image -
Getting Id using Foreign Key in django
Hy Everyone... I have five models in django.. 1- Egg 2-SaleInvocie 3-SaleInvocieItem 4-PurchaseInvocie 5-PurchaseInvocieItem My Scenario is I am making a Sale Return where I am searching for a sale invoice id and select any one id when I select the id it automatically fills the data of that invoice which includes (sale invoice and sale invocie item data). But when I save this it only saves the Sale Return data(which is actually sale invocie data that we retrieves through searching its id) it is not saving the sale return item data (which is actually sale invoice item data), because it i snot getting the id of that hidden input that stores the itme id. and shows me this message in terminal saleReturnItemName [] and my models are this class SaleInvoice(models.Model): user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) searchCustomer=models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customersaleinvoice',null=True) PAYMENT_CHOICES = ( ('paid', 'Paid'), ('unpaid', 'Unpaid'), ) paymentType = models.CharField(max_length=15, choices=PAYMENT_CHOICES,default=None) SHIPMENT_CHOICES = ( ('1', 'Delivery'), ('2', 'Pick Up'), ) shipmentType=models.CharField(max_length=1, choices=SHIPMENT_CHOICES,default=None) searchVehicle=models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name='vehiclesaleinvoice',null=True) searchDriver=models.ForeignKey(Driver, on_delete=models.CASCADE, related_name='driversaleinvoice',null=True) selectNTNInInvoice=models.ForeignKey(NTN, on_delete=models.CASCADE, related_name='selectntn',null=True) invoiceDate=models.DateField(blank=True, null=True) totalSaleAmount=models.CharField(max_length=15,null=True) saleInvoiceAmount=models.CharField(max_length=15,null=True) saleInvoiceDiscount=models.CharField(max_length=15,null=True) STATUS_CHOICES = ( ('in_progress', 'In Progress'), ('delivered', 'Delivered'), ('not_delivered', 'Not Delivered'), ) shipmentStatus = models.CharField(max_length=20,choices=STATUS_CHOICES,default='in_progress',) class SaleReturn(models.Model): user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) … -
Django : stripping HTML after a search filter with dynamic parameters
Some of my database entries contains HTML, and I found here a way exclude HTML from the search so that a user who searches "strong" doesn't get any entry that contains a tag for example. The issue here is that my search contains a dynamic variable wordcontentfilter that looks into a Sense ForeignKey that is "linked" to Mot and that I don't know how to write the part of the if code if query not in strip_tags(i.wordcontentfilter) properly. The other conditions and gramGrp_pos not in strip_tags(i.gramGrp_pos) and gramGrp_gen not in strip_tags(i.gramGrp_gen) and query not in strip_tags(i.slug) works but I need to filter the dynamic part of the search. Any help please ? # We build the request. This request searches into wordcontentfilter = 'sense__' + wordcontent + '__' + search_type print("wordcontentfilter >>> ", wordcontentfilter) filterResult = Mot.objects.filter( Q(**{ wordcontentfilter: query }), Q(gramGrp_pos__icontains = gramGrp_pos), Q(gramGrp_gen__icontains = gramGrp_gen) | Q(slug__icontains = query) ).order_by("slug").distinct() # We strip HTML from results. If user searched a string which can be found in an HTML tag (ex: <strong>), this search result will be removed if filterResult: for j,i in enumerate(filterResult): if query not in strip_tags(i.wordcontentfilter) and gramGrp_pos not in strip_tags(i.gramGrp_pos) and gramGrp_gen not in strip_tags(i.gramGrp_gen) …