Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Resolve AnonymousUser in Django
I have some problems when i create send email form using Django. the problem is when i cliked for send button in contact form. I see this problem. settings.py script here : """ Django settings for Connecting_System project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-ix)p!+kk@f=47&2$%!7w98uflur_!n9o!tr77x3=r=4^r6b%bh' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login.apps.LoginConfig', 'Home.apps.HomeConfig', 'logout.apps.LogoutConfig', 'signup.apps.SignupConfig', 'contact.apps.ContactConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Connecting_System.urls' 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', ], }, }, ] WSGI_APPLICATION = 'Connecting_System.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
It is impossible to add a non-nullable field 'id' to video without specifying a default
This is my models.py from ast import Delete from email.policy import default from django.db import models from django.contrib.auth.models import User class Video(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title=models.CharField(max_length=100, null=False) description=models.TextField(max_length=1000,null=True) video=models.FileField(upload_to="video/%y",null=False) def __str__(self): return self.title class Euser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=10,null=True) birthdate = models.DateField(null=True,) profile_pic = models.ImageField(null=True, ) cover_pic = models.ImageField( null=True, upload_to="images/%y") def __str__(self): return self.phone when i try to makemigrations It is impossible to add a non-nullable field 'id' to video without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. This error occurs... Please suggest me what should i do and also suggest me about any changes in model -
Is it possible to get django info without running it
I have a django model, the whole code is completed. but I want to access my model info. a code like this to get field names. for f in myModel._meta.fields: print(f.get_attname()) is it possible to do it from an external python script without running django server? other possible automated ways of doing this and saving results to a file are also appreciated. -
no such table: django_plotly_dash_statelessapp
I'm trying to deploy my app through Render app, and everything is good, except for the HTML link, it shows"no such table: django_plotly_dash_statelessapp". Not really sure how to solve that. Also, does anyone know which app is free for deployment, I used to use Heroku, but they eliminate the free one from November.no such table: django_plotly_dash_statelessapp -
Cannot set up Oracle bucket for django static files storage
I've been trying to set my bucket as django static file storage, but I keep getting this error: botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden Fyi I'm using an oracle customer secret key as the AWS_SECRET_ACCESS_KEY, as instructed in: https://docs.oracle.com/iaas/Content/Object/Tasks/s3compatibleapi.htm I'm also sure that the information on the parametres is valid: ORACLE_BUCKET_NAME = '<snip>' ORACLE_BUCKET_NAMESPACE = '<snip>' ORACLE_REGION = 'sa-saopaulo-1' AWS_ACCESS_KEY_ID = '<snip>' AWS_SECRET_ACCESS_KEY = '<snip>' AWS_STORAGE_BUCKET_NAME = ORACLE_BUCKET_NAME AWS_S3_CUSTOM_DOMAIN = f"{ORACLE_BUCKET_NAMESPACE}.compat.objectstorage.sa-saopaulo-1.oraclecloud.com" AWS_S3_ENDPOINT_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}" AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = '' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/{ORACLE_BUCKET_NAME}/" -
Deleting user affects incremental unique reference which uses count of matching results. How to keep increment?
For a variety of reasons I might need to delete a user. A soft delete in which I simply delete all identifiable info and leaving some anonymised might not be an option. Additionally, if I delete the user inside the django admin site then it would be a hard delete. The issue is that I have a model for the user which includes first_name, last_name, company_name, reference_id etc. The reference_id is created by using first 3 consonants of the last name, first 3 letters of the first name and then an incremental 3 digit number starting with 001. If any of the names have less than 3 letters the missing letters are replaced with an 'X'. The numeric part uses a model lookup with first 6 letters, counting the number of results. incrementing by 1 and using zfill to fill the missing number of digits. A full reference_id is like this: MDVTAS001 for example: first_name_tres = first_name.lower()[0:3].ljust(3,'x') print("first name 3: " + first_name_tres) last_name_tres = last_name.lower().translate({ord(i): None for i in 'aeiou'})[0:3].ljust(3,'x') print("last name 3: " + last_name_tres) user_ref_count = str(ProfileMember.objects.filter(reference_id__contains=(last_name_tres + first_name_tres)).count()+1).zfill(3) print("user ref count: " + user_ref_count) reference_id = last_name_tres + first_name_tres + user_ref_co The issue with this method … -
How to filter a queryset of Tag objects by current user
I need to filter tags by current user, in serializers class I can not do request -queryset=TagPrivate.objects.filter(user=self.request.user) serializers.py class DotPrivateSerializer(serializers.ModelSerializer): tag = serializers.PrimaryKeyRelatedField( many=False, queryset=TagPrivate.objects.all() # <-------------------------- filter by user ) class Meta: model = DotPrivate fields = ('id', 'name', 'description', 'lat', 'lon', 'rating', 'link', 'tag') read_only_fields = ('id',) ...so is there any way to do it in views.py? class DotPrivateViewSet(viewsets.ModelViewSet): serializer_class = serializers.DotPrivateSerializer queryset = DotPrivate.objects.all() authentication_classes = (JWTAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): """"Return objects for the current authenticated user only""" return queryset.filter(user=self.request.user) -
i am getting a 'Application Error' while hosting django project on heroku
recently i have tried to host my first django project on heroku, but i am getting the following error "An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail" this is a link of my github repository...........https://github.com/derexes292/onlinetest.......... i have put the screenshot of error and logs in the 'error screenshot' folder please help me, i have been working on this problem from a long time but i am not getting any solution. -
DRF display changes that occurred between entries
I have a simple app that displays user entries. Entries are provided manually in Django admin for simplicity's sake class UserEntries(models.Model): user_email = models.CharField(max_length=40) user_custom_id = models.CharField(max_length=40) event_time = models.DateField(auto_now_add=True) event_type = models.CharField(max_length=20) user_city = models.CharField(max_length=20) user_street = models.CharField(max_length=20) What I want to do I to have an endpoint that displays changes between entries with a particular id So let's say I have 3 entries for id of 1 user_email = "test@gmail.com" user_custom_id = 1 event_time = "2022-08-26" event_type = "CREATE" user_city = "Boston" user_street = "Random-str" user_email = "test@gmail.com" user_custom_id = 1 event_time = "2022-08-26" event_type = "UPDATE" user_city = "Boston" user_street = "Park-AVE" user_email = "test@gmail.com" user_custom_id = 1 event_time = "2022-08-26" event_type = "DELETE" user_city = "" user_street = "" So if I query for this particular ID I will get some sort of JSON obj of changes in some form I don't have any preferred style for this JSON obj because I don't know if it's even possible -
How to execute remotely a Celery task with different arguments, asynchronously?
I build a distributed application with Django and the project in server A needs to execute remotely a Celery task in servers B, C, D (...), with thousands of different arguments, asynchronously. What is the best way to achieve that ? Considerations Task's return could stay in servers B, C, D (...); Server A is located in different areas than other servers; Performance is important. One idea I would like to explore is to POST a list of arguments in each remote server and execute the tasks asynchronously there, with apply_async(). But it's not clear for me how a POST request can trigger a Celery task. Here I'm assuming that send_task() is not asynchronous, so I don't think that's an option to consider. Or, perhaps multiple Redis streams could deliver 10,000 messages to all servers without increasing the risk of losing messages along the way. Not sure, but it doesn't sound like the best idea. Would love to hear your thoughts, Thanks -
How to set a default date dynamically in DateField
I'm trying to add a field today + 7 days as a default value in the Django DateField. That's How I'm doing. date_validity = models.DateField(default=datetime.date.today() + timedelta(days=7)) But that's giving me the problem One thing is Field is being altered every time when we run makemigrations/migrate command however we are not making any changes. How can I set that up accurately? -
When user registration data once it fill his city name next time he will same city name it will give error .how it will solved in django
We have data {"id":"1","city":"noida","age":22} But next time he will put same city it will give error.how we can write logic for POST method in view.py file or serialized.py file. -
Django rest framework: how to create a file from string, pass it to serializer and save it?
I need to convert a string to a file, pass it to serializer and save. I'm making a POST request from a fetch in javascript: fetch(`http://127.0.0.1:8000/api/v1/my-end-point/`, { method: 'POST', headers: { Authorization: `Token ${myToken}` }, body: JSON.stringify(obj) }) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); And in django, I have a model like this: # models.py class MyModel(models.Model): file = models.FileField(upload_to='static/directory/') field2 = models.CharField(max_length=100) field3 = models.CharField(max_length=100) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) ... a serializer: # serializers.py class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' and a view: # views.py @api_view(['POST']) @parser_classes([JSONParser,]) def gen(request, format=None): body_dict = json.loads(request.body) body_dict['user'] = request.user.id serializer = MyModelSerializer(data=body_dict) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The POST request is successful and I receive the body in the django's view. I've printed the result in the console: # print(body_dict) {'file': "console.log('string to file test');", 'field2': 'str field2', 'field3': 'str field3', 'user': 2} The file content that I want to save is: console.log('string to file test'); So, how can I convert this string to a file object, name it, pass it to the serializer and save it? -
displaying image in react that is stored in my django backend
I am currently facing a rather strange issue and was wondering if anyone would know the solution. I am making an api call to my Django backend to get details on profiles export const ProfilesPage = () => { const classes = useStyles() useEffect(() => { getProfiles() }) const [profiles, setProfiles] = useState([]) let imgLink = '' let getProfiles = async () => { let response = await fetch('http://127.0.0.1:8000/api/profiles', { method: "GET" }) let data = await response.json() // console.log(data[0].profile_image) imgLink = 'http://127.0.0.1:8000' + data[0].profile_image console.log(imgLink) } return ( <div className={classes.root}> ProfilesPage <img alt='profile' src={imgLink} /> </div> ) } the last line of my getProfiles function I am console.loging the image link. The link is appearing on my console and when i click on it, the correct image is being opened in my browser. I am unsure why react is not displaying the image when the link is clearly working. Thank you, -
Docker django postgres role does not exist
I've been having this error where docker continuously tells me that there isn't a user postgres. After searching around for quite some time, I've come to understand adding environment: - POSTGRES_DB=iku - POSTGRES_USER=admin - POSTGRES_PASSWORD=password This creates a user admin and not the default postgres. This is the error I'm getting src-postgres-1 | 2022-08-26 18:03:00.136 UTC [207] DETAIL: Role "postgres" does not exist. src-postgres-1 | Connection matched pg_hba.conf line 100: "host all all all scram-sha-256" I do not face this error when I port forward to my machine. That is after adding this ports: - "5432:5432" If I do remove the above code, everything works fine. But I cannot connect PGAdmin to the Postgres running on docker as the port is not exposed to the outside. This port tells me role postgres does not exist. Any help would be appreciated! This is my docker-compose file version: "3.9" services: postgres: image: postgres:14.5 volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=custom - POSTGRES_USER=admin - POSTGRES_PASSWORD=password ports: - "5432:5432" redis: restart: always image: redis:latest ports: - "6379:6379" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - postgres - redis I thought I might be having a local postgres … -
How to use nextLink property in Azure Python SDK while listing all VMs
I am trying to list all virtual machines in a subscription in Azure using the code given here: from azure.mgmt.compute import ComputeManagementClient from azure.identity import ClientSecretCredential credentials = ClientSecretCredential( client_id='', client_secret='', tenant_id='' ) subID= '' computer_client = ComputeManagementClient(credentials,subID) vms = computer_client.virtual_machines.list_all() for vm in vms: print( vm.name ) This works fine. It is listing all the vms for the first page. However, how do I get the next_link property and consume the next page of VMs? What would be the syntax? In the docs: https://docs.microsoft.com/en-us/python/api/azure-mgmt-compute/azure.mgmt.compute.v2019_07_01.models.virtualmachinelistresult?view=azure-python it says: next_link str Required The URI to fetch the next page of VMs. Call ListNext() with this URI to fetch the next page of Virtual Machines. I am just wondering what the syntax would look like to consume the next_link property and make the ListNext() call? -
My Wikipedia-inspired Django project returns an error whenever I click an entry
I work with Django to create a Wikipedia-like app (course project). When I click one of my entries, I receive the following error: TypeError: entry() got multiple values for argument 'title' Here the view I created for entries in views.py: @csrf_exempt def entry(request, title): flag = util.get_entry(title) if flag is None: form = SearchForm() content = "The page you look for does not exist :(" return render(request, "encyclopedia/error.html", {"form": form, "content": content}) else: form = SearchForm() mdcontent = util.get_entry(title) htmlcontent = markdowner.convert(mdcontent) return render(request, "encyclopedia/entry.html", { "title": title, "content": htmlcontent, "form": form }) Do you notice multiple values for title? I'm new to Django and can't figure out the problem. Your help will be appreciated. -
Using ModelSerializer class nested inside Serilaizer class to validate field and return object
I'm trying to validate user input by passing the data to a Serializer class. The said serializer class has no models and inherits from serializers.Serializer. I'm trying to validate if the input is present in a ModelSerializer class called Country. My code keeps returning the following error: value already exits. Things I have tried: field level validation using a method called: validate_country - which works. I wanted to know if the same could be achieved by calling Country serializer class from inside ValidationSerializer. models.py class Country(models.Model): iso_code = models.CharField(max_length=2, unique=True) name = models.CharField(max_length=255) class Meta: ordering = ("name",) verbose_name_plural = _("Countries") def __str__(self): return self.name serializers.py class CountrySerializer(serializers.ModelSerializer): class Meta: model = Location fields = ("id", "name", "iso_code") class ValidationSerializer(serializers.Serializers): # this serializer does not have a model and only want to validate inputs provided by user country = ListField(child=CountrySerializer(many=False, required=False), default=list, allow_empty=True) # sample country input looks like: {"country": ["US", "CA", "GB"]} # I want to pass the country codes to CountrySerializer to validate if the country codes exists and return a seriliazed object views.py class MyView(GenericAPIView): def get(self): country=request.query_params['country'].split(",") ser = ValidationSerializer(data=country) if not ser.is_valid() return Response(ser.errors) else: #process request Thank you ! -
Edit the code of module in venv during docker build in Django + React app
I have React as frontend and Django with Django REST Framework working as API. And the issue is I changed several lines of code in module I installed for Django app. Obviously, during Docker build those changes aren't saved. Because .venv folder for virtual environment isn't copied to container. I'm asking a way to make changes to module in .venv folder during build. The number of changes isn't huge. Only two lines. The module is django-rest-multiple-models==2.1.3(https://pypi.org/project/django-rest-multiple-models/) In drf_multiple_model folder which is I believe a main folder of the module in .venv I changed following(lines 196-207): def get_label(self, queryset, query_data): """ Gets option label for each datum. Can be used for type identification of individual serialized objects """ if query_data.get('label', False): return query_data['label'] elif self.add_model_type: try: return queryset.model._meta.verbose_name except AttributeError: return query_data['queryset'].model._meta.verbose_name There was __name__ instead of verbose_name Dockerfile in Django app: FROM python:3.10-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /server COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . docker-compose.yml: version: '3' services: backend: build: context: ./server command: gunicorn core.wsgi --bind 0.0.0.0:8000 ports: - "8000:8000" expose: - 8000 depends_on: - postgres -
Post method to pass data to multiple model serializers
I am new to Django and have a json object whose data has to be split and stored in 3 different Django models. I'm trying to figure out if I'm doing this correctly in using the view file and serializers in Django. The json object that I receive into the views file looks like below: [ { "contact_entry": { "employee_name" : "Tom Hanks", "employee_type" : "Full-time permanent" }, "address" : { "line1": "1435 Manhattan Ave", "line2": "Apt 123", "city": "New York", "state": "New York", "country":"US", }, "phone_number" : { "work_number": "9901948626" "home_number": "9908847555" } } ] I have three django models as shown below: class ContactEntry(models.Model): employee_name = models.CharField(max_length=128) employee_type = models.CharField(max_length=128) class Address(models.Model): contact_entry = models.ForeignKey(ContactEntry, on_delete=models.CASCADE) line1 = models.CharField(max_length=128) line2 = models.CharField(max_length=128) city = models.CharField(max_length=128) state = models.CharField(max_length=128) country = models.CharField(max_length=128) class PhoneNumber(model.Model): contact_entry = models.ForeignKey(ContactEntry, on_delete=models.CASCADE) work_number = models.IntegerField(max_length=10) home_number = models.IntegerField(max_length=10) Each of them has a ModelSerializer as shown below: class ContactEntrySerializer(serializers.ModelSerializer): class Meta: model = ContactEntry fields = '__all__' class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' class PhoneNumberSerializer(serializers.ModelSerializer): class Meta: model = PhoneNumber fields = '__all__' I have defined one serializer (inherited from serializers.serializer) that combines the above 3 serializers as shown … -
Path duplication in href
I'm new to Django and I'm trying to create web viewer for myself that browses static folder to open subfolders and .mp4 files. Problem occurs when I open second child of static folder: links break and start duplicating path. Example: Static folder structure: - static folder - folder - videos -videos_1 -videos_1_1 -videos_1_2 -videos_2 When root and first child folders are viewed, all HTML links work as needed and lead to next subfolders or files (links look like localhost:8000/videos/videos_1). When second child folder is viewed, it's content is displayed, but all links are broken, for example when folder videos_1 is viewed, links look like localhost:8000/videos/videos/videos_1/videos_1_1, however, when HTML is inspected, link is <a href="videos/videos_1/videos_1_1"></a>. urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', folderViewer, name='files'), path('<path:kw>', folderViewer),] views.py: def folderViewer(request, kw=''): path = os.path.join(STATIC_URL, kw) if os.path.isdir(path): files = os.listdir(path) paths_files = [] for i in range(len(files)): paths_files.append([kw + '/' + files[i], files[i]]) context = { 'files': files, 'paths_files': paths_files, } return render(request, 'files.html', context) files.html: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>files</title> </head> <body> {% for i in paths_files %} <div> <a href="{{ i.0 }}">{{ i.1 }}</a> </div> {% endfor %} </body> </html> -
Trying to filter of data based upon child's child model set Django
Trying to create a function based where the executive get's options based upon the pincodes. Tried this method but it's not working out can anyone please help? Thanks in advance... (Don't judge the code because this a early stage development and I'm a beginner developer so sorry if the code isn't proper to read) Models.py class User(AbstractUser): ADDCHKS_ID=models.CharField(max_length=16) is_active=models.BooleanField(default=False) is_excutive=models.BooleanField(default=False) class ExcutiveRegistration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) '''Personal Details''' First_name = models.CharField(max_length=100) Last_name = models.CharField(max_length=100) DOB = models.DateField(max_length=100) Fathers_name = models.CharField(max_length=100) Contact_number = models.IntegerField(max_length=10) Alt_Contact_number = models.IntegerField(max_length=10) # Profile_picture=models.ImageField(upload_to='images/', null=True, verbose_name="") '''Current Addresss''' Pin_code_c = models.IntegerField(max_length=6) State_c = models.CharField(max_length=50) District_c = models.CharField(max_length=50) Taluk_c = models.CharField(max_length=50) Location_c = models.CharField(max_length=100) House_no_c = models.IntegerField(max_length=4) Street_c = models.CharField(max_length=100) '''Permanent Address''' Pin_code_p = models.IntegerField(max_length=6, null=True) State_p = models.CharField(max_length=50, null=True) District_p = models.CharField(max_length=50, null=True) Taluk_p = models.CharField(max_length=50, null=True) Location_p = models.CharField(max_length=100, null=True) House_no_p = models.IntegerField(max_length=4, null=True) Street_p = models.CharField(max_length=100, null=True) '''Reference''' Family_reference_name = models.CharField(max_length=100, null=True) Family_reference_conatact_number = models.IntegerField(max_length=10, null=True) Neighbour_reference_name = models.CharField(max_length=100, null=True) Neighbour_reference_contact = models.IntegerField(max_length=10, null=True) '''Document Proof''' ID_Proof_Document_Type=models.CharField(max_length=50, choices=ID_CHOICES, default="Voter", null=True) class ExcutiveRegistrationPincode(models.Model): ExcutiveRegistration=models.ForeignKey(ExcutiveRegistration, on_delete=models.CASCADE) Covering_Pincode=models.IntegerField(max_length=6) class Customer(models.Model): # user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) Verification=models.CharField(max_length=50, choices=Verification_Method, default=None, null=True, blank=True) Client_ID=models.CharField(max_length=20, null=True,blank=True) Client_name=models.CharField(max_length=50,blank=True) Applicant_Name=models.CharField(max_length=50,blank=True) DOB=models.DateField() Father_name=models.CharField(max_length=50, null=True,blank=True) Pincode=models.IntegerField(max_length=6, null=True,blank=True) Present_address=models.CharField(max_length=300, null=True,blank=True) Permanent_address=models.CharField(max_length=300, null=True,blank=True) Contact_number=models.CharField(max_length=11, null=True,blank=True) … -
images content-type are text/html [closed]
I have created a site with django and it was working fine but now all the images disappeared. I've found out that the content-type of images are now text/html instead of image/jpeg. Although there are many topics about this issue i couldn't solve the problem. ` {% thumbnail product.productImage1 "500x500" crop='center' as im %} <a href="{% url 'product_detail' brand=product.productBrand.url_title productType=product.productType product_slug=product.productSlug %}" style="float: left"> <img src="{{ im.url }}" alt="" > </a> {% endthumbnail %}` addressing the image in URL my products page -
Update a BLOB Image stored in MySQL Database with Django
I'm storing the images in mysql in a Blob format (BinaryField in Django), the action of adding the image is proecssed well and i can display them easily by adding to the string 'data:image.....'. The problem is when I try to update an already stored BLOB Image in the database with django. -
How can I add cryptocurrency payments to a Django ecommerce?
I want a Django website capable of accepting at least Bitcoin and Monero but I don't know what tools to use and how a system like that would work. My first question is how does a cryptocurrency payment system even work, how could I generate each user a wallet so they could add a certain amount of crypto to it? My second question is in where and how would the users send the crypto they've added to the vendor after they buy something, with some market fees.