Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django make migrations contanstly creates AlterField for many-to-many field
I have a very annoying situation with my model I renamed a Model used as ManyToMany table # The business models contains this field admins = models.ManyToManyField("users.User", through=BusinessMember) # this is the many to many model used in in Business class BusinessMember(models.Model): user = models.ForeignKey( "users.User", related_name="memberships", null=False, on_delete=models.CASCADE ) business = models.ForeignKey( "business.Business", related_name="members", null=False, on_delete=models.CASCADE ) class Meta: db_table = "myproject__business_member" This model once was called "BusinessUser" and I had to rename it. I created the following migrations to rename the Model # Rename and alter model table 0011_rename_business_user_model.py class Migration(migrations.Migration): dependencies = [ ("business", "0010_add_business_field"), ] operations = [ migrations.RenameModel("businessuser", "businessmember"), migrations.AlterModelTable( name="businessmember", table="myproject__business_member", ), ] # Another migration to update the sequence class Migration(migrations.Migration): dependencies = [ ("business", "0011_rename_business_user_model"), ] operations = [ migrations.RunSQL( "alter sequence myproject_business_user_id_seq rename to myproject__business_member_id_seq;" ), ] After this change, the makemigrations constantly create a migration with this AlterField migrations.AlterField( model_name='business', name='admins', field=models.ManyToManyField(through='business.BusinessMember', to=settings.AUTH_USER_MODEL), ), It doesn't matter how many times I migrated this AlterField, Django creates another migration every time. Do you have any idea what I did wrong? -
How to pass data to a template without passing it through the view?
I have a base.html file where on the sidebar it loops through all the spaces inside of my Spaces model and displays them as links. I am wondering instead of passing these spaces through each view is there a way to just have them in the base template? I tried looking it up an came across template tags but I don't think those are what I am looking for. Base.html <div class="sidenav"> <h2>Spaces:</h2> {% for space in spaces %} <a href="/{{space}}">{{space}}</a> {% endfor %} </div> Right now I am passing 'spaces' through my views but I don't want to have to do that in each view i create. Any help would be appreciated! -
How to resolve code duplication in View for model instances filtering
I trying to figure out how to resolve probably a very simple issue, but I would like to do it in an appropriate and Django consistent way. Let's assume that we have an example model: class ExmapleModel(Model): vote_up = models.IntegerField(default=0) vote_down = models.IntegerField(default=0) def get_voting_count(self): return self.vote_up - self.vote_down Ok and now I would like to create separate views on one template for ExmapleModel which will have for instance voting count higher than 500 and for all instances. Of course, I could create something like: class ModelListView(ListView): model = ExmapleModel template_name = 'ExmapleModel_list.html' and the second one: class ModelListView(ListView): model = ExmapleModel template_name = 'ExmapleModel_list.html' queryset = ExmapleModel.objects.filter(get_voting_count()>300) Assuming all the above, I would like to prevent repeating a lot of code for the above example, I have no idea how to user a get_voting_count() method for filtering and combining all of those things for the working package. If you have any ideas on how to combine it please help me. On other hand should I use this logic within Model? -
How can I use the same mock database both while testing normal django views and api views?
I have a following problem: I run tests using TestCase and create some data for my database. However, before rendering the template the view uses some API calls and receives information from the real database instead of the mock one. Is there a way to solve this problem? Or maybe I should test the view and the API view separately? Maybe I should create APITestCase? Any help will be appreciated. -
How to get "Historical" Queryset for the dataset using Django ORM?
I have CurrencyHistory model along with the database table which is populated on every Currency model update for the historical data. class CurrencyHistory(models.Model): id = models.AutoField(primary_key=True) change_rate_date = models.DateTimeField(_("Change Rate Date"), auto_now=False, auto_now_add=True, db_column='change_rate_date') code = models.ForeignKey("core.Currency", verbose_name=_("Code"), on_delete=models.CASCADE, related_name='history', db_column='code') to_usd_rate = models.DecimalField(_("To USD Rate"), max_digits=20, decimal_places=6, null=True, db_column='to_usd_rate') Database structure looks like id | change_rate_date | code | to_usd_rate 1 | 2021-01-01 | EUR | 0.123456 2 | 2021-01-01 | CAD | 0.987654 3 | 2021-01-02 | EUR | 0.123459 4 | 2021-01-02 | CAD | 0.987651 I need to fetch data using Djnago ORM to have a dictionary to display single row per date with the every currency as columns, like this Date EUR CAD 2021-01-01 0.123456 0.987654 2021-01-02 0.123459 0.987651 But I have no idea how to correctly do it using Django ORM to make it fast. I suppose for loop over the all unique database dates to get dict for each data will work in this case but it looks very slow solution that will generate thousands of requests. -
Django queryset filtering not providing expected behavior
I have an app taking inputs from a user on the front end. The functionality I'm trying to implement should display all titles on the front end that have reviews <=0, or display NULL values in the database. reviewsign_high = 'lte' if reviewinput_high == '0': review_kwargs = { 'amz_reviews__isnull': True, 'amz_reviews__{}'.format(reviewsign_high): float(reviewinput_high) } titles = titles.filter(**review_kwargs) However, I don't get any results back here. If I remove one parameter, i.e. 'amz_reviews__isnull': True, I do get all titles with reviews less than or equal to 0. Vice versa, if I remove 'amz_reviews__{}'.format(reviewsign_high): float(reviewinput_high), I get all titles with NULL reviews. But them together, displays 0 results. Any ideas on a solution here? Thanks! -
changing color of a particular string in entire html document with Django
Suppose you have a word "day" in 100 sentences in your document. You can change the color of that word in the following way: <span style="color: #ff0000"> day </span> The problem is that you need to do it 100 times. I am using Django and I want to do it inside template with for loop. So, my problem is now to change the color of a string inside some sentence that I don't know what it will be. I tried with something like: def colored(sentence, string, color): if string not in sentence: return sentence else: colored_string = f'<span style="color: {color}"> {string} </span>' colored_string.join(sentence.split(string)) I thought that that will give me colored variable string, but that wasn't the case. It just returned the string '....<span....' without any including the same stuff. It just like it didn't recognized html at all. What is the correct way of solving the same problem? -
What does request.POST.get method return in Django?
What does request.POST.get("a") return while "a" is the reference to following html label for = "a">ADDED ITEMS:</label> <input hidden type="number" name="a" id="a"> def myfunc(): if request.method == "POST": a = request.POST.get("a"); obj = TransferedItems(item_id = a); obj.save(); return HttpResponse("sent") else: return HttpResponse("form submission failed") I am new at Django and I am unable to find what does request.POST.get return. Please guide me on my question. -
Why my code Django into HTMl variables didnt work
''' Im trying to get a variable into a html document with python and django ''' def nombrarVariables(request): nombre="juan" doc_externo=open("SeleccionGrafica2.html") template=Template(doc_externo.read()) doc_externo.close() contexto=Context({"variable": nombre}) documento=template.render(contexto) return HttpResponse(documento) -
how to get the instance of a newly created user in django function based view
i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and right now, i know what to do but i don't know how to implement maybe becuase i don't have much experince with django. i defined an instance variable to store all the newly created information but i'm just stock and it keeps showing red underlined word in vsCode, Any help would be greatly appreciated views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') # error is showing "instance" is not access using visual studio code instance = UserMembership.objects.create(user=obj, membership=get_membership) messages.success(request, f'Account Successfully created for {username}! You can Login In Now') return redirect('userauths:login') elif request.user.is_authenticated: return redirect('elements:home') else: form = UserRegisterForm() context = { 'reviews': reviews, 'form': form, 'info': info, 'categories': categories } return render(request, 'userauths/register.html', context) traceback Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in … -
Image stored in media is not been displayed
when click on "yo" image is shown but when displayed through img tag its not appearing on webpage <a href="{{status.adv.url }}">yo</a> <img src="{{status.adv.url}}" width="250" height="250" alt="advertise"/> -
Is there any way to edit django template?
In the last part of the code there exists a for loop which helps in constructing the boostrap crousel , but to make the website responsive i need to remove that forloop . So is there any way achive responsiveness? <div class="carousel-item active"> {% for i in products %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top mt-2" alt="..."> <div class="card-body"> <h5 id="productName{{i.id}}" class="card-title">{{i.product_name}}</h5> <p id="productPrice{{i.id}}" class="card-text">₹ {{i.price}}</p> <span id='button{{i.id}}'> <div id='product{{i.id}}' class="btn btn-primary cart">Add to cart</div> </span> <a href="/shop/productView/{{i.id}}" id="quickView{{i.id}}" class="btn btn-primary ml-3">Quick view</a> </div> </div> </div> {% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> -
Django - deployment Heroku, how to solve error server (500)? Cloudinary error?
I have a question about my deployment app Django on Heroku. Whenever it is Debug=False in the setting.py file, it returns Error server 500, and when True then it is, ok? It is with the collecstatic parameter? find below the setting file: Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ import os from pathlib import Path import django_heroku import cloudinary.api import cloudinary_storage # 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ecom-beta-XXXXX.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store.apps.StoreConfig', 'cloudinary', 'cloudinary_storage', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'ecommerce.wsgi.application' # Database # … -
Adding data to form before it submits via Javascript in Django
I am working on an app in Django where the user puts in their address and submits it in a form. I need to get this form data, along with its corresponding lat/long, into the views and save it in a model. So, I have used Javascript to call a lat/long API before the form submits and then add that data to the form so all of the data (the address and the lat/long) gets submitted to the server. However, this newly inserted data by Javascript does not show up with the rest of the POST data when submitted. I am not sure why this is. Here is the JS code: const initiate_ride_form = document.querySelector("#initiate-ride-form"); if (initiate_ride_form != null) { document.querySelector("#start-ride-button").onclick = () => { // these are just predecided addresses to simplify the code and isolate this problem const origin = '20%20W%2034th%20St%2C%20New%20York%2C%20NY%2010001' const destination = '1600%20Pennsylvania%Avenue%20NW%2C%20Washington%2C%20DC%2020500'; fetch(`https://api.opencagedata.com/geocode/v1/json?q=${origin}&key=b45938af46624365b08b989268e79d5e`) // Put response into json form .then(response => response.json()) .then(data => { // get the lat and long and save them in variables console.log(data.results[0].geometry); const longitude_origin = data.results[0].geometry.lng; const latitude_origin = data.results[0].geometry.lat; // add the make the hidden input's value equal to the long var input_long_origin = document.querySelector("#from_long"); input_long_origin.value = longitude_origin; // … -
How do I make an upload pdf and make it render to my page in django?
Right now I just have it so that in the admin site when the admin writes out the form and clicks send it has a button that says view on the page and you click it, it brings you to a pdf. How do I make it so that the admin can just upload a pdf from the admin site and make it render for all the users? -
How to precache/load remote postgres DB in django/python for faster testing?
I am running django with a remote heroku hosted DB for testing. When developing locally/testing I am using the remote DB. Is there a way to precache/load the entire database locally so that I don't have to do network calls when running queries? Otherwise, I am using lru_cache in python for certain queries. Is there something I'm missing where I can just fetch the whole thing and cache it? -
two formsets in one view - django
i'm trying to implement two formset in one view , one of the formsets should be pop up modal form , class MobileCollection(models.Model): mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) serial_no = models.CharField(max_length=7,unique=True,blank=True,null=True) status = models.BooleanField(default=True) def __str__(self): return f'{self.mobile}-{self.imei}' in the page we adding new instance of MobileCollection , and each MobileCollection have its own set of imei , if qnt = 10 then we have to add 10 imei @login_required def create_collection(request): item_formset = mcollection(queryset=MobileCollection.objects.none()) imei_formset = imei_modelformset(queryset=Imei.objects.none(),prefix='imei') if request.POST: item_formset = mcollection(request.POST) imei_formset = imei_modelformset(request.POST,prefix='imei') if imei_formset.is_valid() and item_formset.is_valid() and request.user.is_superuser: for item in item_formset: item_obj = child.save(commit=False) item_obj.save() for imei in imei_formset: imei_obj = imei.save(commit=False) imei_obj.mobile = item_obj imei_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({ 'success':False,'error_child_msg':item_formset.errors,'error_imei_msg':imei_formset.errors}) context = { 'item_formset':item_formset, 'imei_formset':imei_formset } return render(request,'storage/collection.html',context) but it only saves the last item entry and doesnt save imei , only its instance(from the item) will be saved these are my formsets mcollection = modelformset_factory( MobileCollection,form=MobileCollectionForm,fields= ['mobile','qnt','price'],can_delete=True,extra=1) imei_modelformset = modelformset_factory(Imei,form=ImeiForm,fields= ['imei'],extra=1,can_delete=True) const addNewRow = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = document.getElementsByClassName('child_forms_row') const countForms = currentFormClass.length const formCopyTarget = document.getElementById('form-lists') const empty_form = … -
Django Project - 'urlpatterns' = (syntax error - cannot assign to literal)....Please advise?
Django Project - 'urlpatterns' = (syntax error - cannot assign to literal)....Please advise? -
The included URLconf 'web_project.urls' does not appear to have any patterns in it
My Customer Apps urls.py ''' from django import urls from django.urls import path from django.urls.resolvers import URLPattern from .import views URLPattern = [ path('', views.base ,name= 'customer-base'), path('Hall/', views.Hall ,name= 'customer-Hall'), path('Food_item/', views.Food_item ,name= 'customer-food'), path('About_us/', views.About_us ,name= 'customer-about'), ] ''' My web_project urls.py ''' from django.contrib import admin from django.urls import path, include from django.urls.resolvers import URLPattern URLPattern = [ path('admin/', admin.site.urls), path('base/', include('customer.url')), ] ''' errors that are showing ''' Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Nawaf Bhatti\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\Nawaf Bhatti\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\utils\functional.py", line 48, … -
How to using two parameters in delete method of class GenericViewSet in Django
I'm newbie Django How can use 2 params on my url with delete method on django 3 My url config: API_VERSION = os.getenv('API_VERSION') API_ROOT = "grpz/" router = routers.DefaultRouter(trailing_slash=False) router.register(r'^groups/(?P<group_id>.)/users/(?P<user_id>.)', group_views.DeleteGroupViewSet) schema_view = get_schema_view( title='next_blog', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]) urlpatterns = [ path('admin', admin.site.urls), path('api_auth', include( 'rest_framework.urls', namespace='rest_framework')), path('docs', schema_view, name='docs'), path(API_ROOT, include(router.urls)), ] My class viewsets: class DeleteGroupViewSet(viewsets.GenericViewSet): queryset = Groups.objects.all() serializer_class = GroupSerializer permission_classes = (AllowAny,) def destroy(self, request, group_id, user_id): try: # user_id = self.kwargs['user_id'] # group_id = self.kwargs['group_id'] user = Users.objects.filter(user_id=user_id).first() if user is None: return Response({ 'msg': 'User is not exist', }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: user_owner_role_in_group = GroupHasUsers.objects.filter( group_id=group_id, user_id=user_id, role__name='owner' ) if user_owner_role_in_group.count() == 0: return Response({ 'msg': 'User is not a owner role' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: Groups.objects.filter(id=group_id).delete() return Response({'msg': 'success'}, status=status.HTTP_200_OK) except Exception as e: return Response({ 'msg': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) Thanks all ! -
Accessing os files with django inside an electron application
I have a web application built with Django/React. I want to convert it to an electron app and am unsure if I need to refactor some of the backend code to node.js. Here is the relevant information: User needs to create a file with their own API token received from 3rd party. I would like to avoid sending their personal token to my server and want to keep it on their operating system. Django uses the token to query data from the 3rd party api. Django sends data back to front end. My question is, once the application is bundled as an electron app, can django access their api token and query the 3rd party api without hitting my server? Will the django code be run on the localhost (or can it) is I guess what I mean. Thanks, hope this is a valid SO question. -
Django modelformset not saving data. Returns empty list after calling cleaned_data
I have a problem with formset, its doesnt save. Console returns no errors but after calling print(formset.cleaned_data) it returns empty list. Standard form saves normally. This formset is for adding a service made to a car object. I couldnt find the answer online, maybe someone will help or find a better solution. models.py class Car(models.Model): FUEL = ( ('', '---------'), ('1', 'Gasoline'), ('2', 'Diesel'), ('3', 'Electric'), ('4', 'Hybrid'), ) client = models.ForeignKey(Client,on_delete=models.CASCADE, null=True, blank=True) car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) car_model = models.ForeignKey(CarModel, on_delete=CASCADE) fuel_type = models.CharField(max_length=15, choices=FUEL, default=None) engine = models.CharField(max_length=15) extra_info = models.TextField(max_length=300, verbose_name='Remarks', null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.client} | {self.car_make} {self.car_model}" class Meta: ordering = ('-date_updated',) class Service(models.Model): car_relation = models.ForeignKey(Car, on_delete=models.CASCADE) service_name = models.CharField(max_length=200, verbose_name='Service') service_price = models.CharField(verbose_name='Price', blank=True, null=True, max_length=20) def __str__(self): return self.service_name forms.py class AddServiceForm(forms.ModelForm): class Meta: model = models.Service fields = ['service_name'] class CarForm(forms.ModelForm): class Meta: model = models.Car fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['car_model'].queryset = models.CarModel.objects.none() # returns no value till "Make" field is chosen, will be negated in elif statement if 'car_make' in self.data: try: car_make_id = int(self.data.get('car_make')) self.fields['car_model'].queryset = models.CarModel.objects.filter(make_id=car_make_id).order_by('model_name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['car_model'].queryset = self.instance.car_make.carmodel_set.order_by('model_name') # … -
how to to check if a value exists in a multiselectfield with django templat language
I am using multiselectfield in the models so that a user can select multiple values and store in a column called sub_law_type. The values are gettting stored correctly in that column. Now in the html I have some conditions that are to be met for the judgement data to be displayed. All the other condtions are being checked correctly but I am confused as to how to check if a value exists in the sub_law_type. here I want to check if the sub_law_type has the value 'ipc' in it then only display the judgement the code below is the way I wrote initially to check if the condition is true but this was not displaying any result {% if data.law_type == 'criminal' and data.sub_law_type.ipc and data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} then i tried writing it as below but even that was not displaying the correct result {% if data.law_type == 'criminal' and data.sub_law_type== 'ipc' and data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} Since both of them are not working I am confused how I should write it so tat i can get the result. models.py sub_type_of_law = ( … -
django model ImageFile upload through code/manually
I am writing a populate script in python to register users and registeration asks them to upload a picture. Now, to achieve it through code, I read various threads of stackoverflow and came up with the 'picture.save' code below to save an image to the ImageField where actually user uploads a image. Below is the snippet of code in my populate_dogpark.py file from django.core.files import File created, __ = Dog.objects.get_or_create(owner=dog['owner'], breed=dog['breed'], breedname=dog['breedname'], name=dog['name'], age=dog['age'], gender=dog['gender']) created.picture.save(dog['path'], File().read(), True) created.save() But, upon attempting to execute this command I get the following error: File "populate_dogpark.py", line 80, in create_dog created.picture.save(dog['path'], File().read(), True) TypeError: __init__() missing 1 required positional argument: 'file' (socialapp) What I want to achieve is that for the following field in my model, picture = models.ImageField(upload_to="dog_profile_picture", blank=True) I want the ImageField to automatically upload picture from the path to file from the static/images directory I will provide in dog['path']. I need help to resolve this error. Stack trace provided above. -
django user authenticate only returns None
i'm trying to create a simple API on Django, and this is my first. The class User get the AbstractUser, like this: from django.db import models from django.contrib.auth.models import AbstractUser class Usuario(AbstractUser): nome = models.CharField(max_length = 255) username = models.CharField(max_length=150, unique=True, blank=False, null=False, default="") nascimento = models.DateField() password = models.CharField(max_length=128, blank=False, null=False, default="") But when I try to authenticate, the method allways returns None. Why? I checked, on DataBase, and the Users are already there. from django.shortcuts import render, redirect from conta.models import Usuario import secrets from django.contrib.auth import authenticate, login def login_view(request): if request.method == "POST": user = request.POST.get("user") senha = request.POST.get("password") autenticador = authenticate(request, username=user, password=senha) if autenticador is None: context = {"error" : "Invalid username or password"} return render(request, "conta/tela_de_login.html", context) login(request, autenticador) redirect('/admin') return render(request, "conta/tela_de_login.html", {})