Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to download images from a template?
Here is my problem. To summarize, my application transform one or many images. And I want that the user can download the images transformed with a button "Save new images" for example. When the user clicks the button, the Download window for example pops up and he can download all the images where he wants on his computer. I don't know if it's possible, I wait your answers. I already did the upload images part, it works. views.py def mon_data(request, dataset_id): my_data = get_object_or_404(Dataset, pk=dataset_id) images_src = Image_Source.objects.filter(dataset = my_data) images_seg = [] for src in images_src: seg_current = Image_Segmentee.objects.get(origine = src, model = src.model_initial) model = images_seg[0].model context = { "material": model.materiau_type, "model": model, "images_seg": images_seg, "my_data": my_data, "nb_images":len(images_seg) } return render(request, "interface/my_data.html", context) models.py TYPES=[ ('Metal', 'Metal'), ('Composite', 'Composite'), ] DECISION=[ ('En attente', 'En attente'), ('Valide', 'Valide'), ('Rejete', 'Rejete'), ] class Modele(models.Model): name = models.CharField(max_length=100) materiau_type = models.CharField(max_length=20, choices=TYPES, null=False, blank=False) class Dataset(models.Model): name = models.CharField(max_length=200, null=False, blank=False) date = models.DateField() class Image_Source(models.Model): dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE, null=True) materiau_type = models.CharField(max_length=20, choices=TYPES, null=False, blank=False) model_initial = models.ForeignKey(Modele, on_delete=models.SET_NULL, null=True) illustration = models.ImageField(null=False, blank=False, upload_to="img/") class Image_Segmentee(models.Model): origine = models.ForeignKey(Image_Source, on_delete=models.CASCADE, null=True) operator_decision = models.CharField(max_length=20, choices=DECISION, default='En attente') illustration … -
Make dynamic migrations to different databases in django in runtime
I am creating a database and storing its details in a core database. I am appending the database configuration values from the core database and populating them in the settings.py like this, from database import database_details for database in database_details: new_databases.append(database) for database in new_databases: DATABASES[database[1]] = { 'ENGINE':database[2], 'NAME': database[4], 'USER':database[3], 'PASSWORD':database[5], 'HOST':database[6], 'PORT':database[7], 'OPTIONS':{ 'init_command':database[8] } } This works perfect when I do migrations manually. When I am adding values to the core database during runtime and running call_commands from django.core import management management.call_command('makemigrations', name=app_name, skip_checks=True) management.call_command('migrate', app_label=app_name,database=database_key,interactive=False, skip_checks=True) the DATABASE dictionary is not getting updated by new values, giving this error. The connection database_key doesn't exist How can I update the values from database in settings.py. I tried calling django.setup before call_commands. Thank you. -
Django RetrieveUpdateAPIView test fails
I am writing a test for a RetrieveUpdateAPIView class and I got an error 415 (Unsupported media type) My test code looks like this: def test_update(self): record = MyObject.objects.first() response = self.client.patch( reverse('update', kwargs={'pk':record.id}), {'date': datetime.datetime.now(), 'amount': 10 }, format = 'application/json' ) updated = SpendingConfig.objects.get(id=record.id) self.assertEqual(updated.amount, 10) The url looks like: path('int:pk/update/', MyUpdateView.as_view(), name='update'), Does anyone know where the problem could be? Thanks in advance. -
Server error (500) when trying to deploy django app with DEBUG=False on heroku
I am trying to deploy an django application on heroku. when the DEBUG variable is False, I receive a server error (500). Everything works fine when DEBUG is True. How to solve this problem ? -
AttributeError 'UserViewset' object has no attribute 'action'
I've been using django rest framework, and I'm trying to customize the get_parsers method in my UserViewset, I looked at the docs, and found similar use case with permission classes in docs, and I tried to customize the get_parsers like this class UserViewset(viewsets.ModelViewSet): serializer_class = UserSerializer # Redefine get_parsers, so that only the update methods have form-data media type def get_parsers(self): if self.action == 'update' or self.action == 'partial_update': parser_classes = [FormParser, MultiPartParser] else: parser_classes = [JSONParser] return [parser() for parser in parser_classes] but I keep getting the error: AttributeError at /api/auth/users/: 'UserViewset' object has no attribute 'action' I tried the use case found in the docs and it worked perfectly. What am I doing wrong here ? -
Django connection error - django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
My Django project fails to connect to postgres database. django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" The settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'PORT': 5432, 'ATOMIC_REQUESTS': True } } The pg_hba.conf file contents: Before, the 'TRUSTED' method was set to 'PEER' by default. By it wasn't working that way. So I changed it to TRUSTED, ran systemctl restart postgresql, and it isn't working now either. I know that postgres password is empty by default, so I tried the following: sudo -u postgres psql postgres=# ALTER USER postgres PASSWORD 'postgres'; The output was ALTER ROLE. But the error from Django still persists. I ran out of ideas. Any hints ? I ran out of ideas. -
Updating multiple tables in Django
I'm new to Django, and DBMS .I have table 1 and table 2, I'm updating both and if table 1 was successfully updated, i ll move to the process of updating table 2 , if there was an error while updating table 2, then i need to revert the changes i made in table 1. how can i achieve that in Django? This is the code i did roughly def user_operation(request, id): if request.method == 'PUT': try: json_fetch = json.loads(request.body) update_emp = EmpDetailsModel.objects.get(emp_id=id) for key,value in json_fetch.items(): flag = 0 if key == 'contact': cont_update = EmpDetailsModel.objects.get(emp_id=id) for contact in value: flag = cont_update.empcontactmodel_set.create(phone_number=contact['number'], dev_type=contact['type']) if flag == 0: return JsonResponse({'Error':'There was an Error !'}) continue flag = update_emp.update(**{key:value}) if flag == 0: return JsonResponse({'Error':'There was an Error !'}) except KeyError: return JsonResponse({'Error':'Invalid Key in request!'}) -
How can I filter a results table with multiple forms/multiple options in one form in django?
I want to have one page with multiple filter options (e.g. Name, Abbreviation, Country, ...) where you can type Sweden in the form and only get the results of Institutions in Sweden OR type the name/abbreviation/... when you press the 'search' button. The search button then redirects you to the filtered result table. forms.py class InstitutionsForm(forms.Form): name = forms.CharField(label='Name', required=False) abbreviation = forms.CharField(label='Abbreviation', required=False) views.py def institution_search_form(request): if request.method == "POST": form = InstitutionsForm(request.POST) if form.is_valid(): return institution_results_name(request, form) else: context = { "form": InstitutionsForm } return render(request,"stakeholders/institution_form.html", context) def institution_results_name(request, form): all_insts = Institution.objects.filter(name=form.cleaned_data["name"]) context = { "result_data":=SafeString(serializers.serialize("json", all_insts)), } return render(request, "landing/result_table.html", context) institution_form.html <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Search"> </form> So far I do get all the CharFields I defined in forms.py on one page. My problem is that I cannot search for the countries, abbreviation, etc. only 'Name' does work. I tried to write different forms and even put them on different urls, but all just filtered after the typed in name. With a country I just get an empty results table. I also tried to write different views for each form and changed 'name' with 'country' everywhere, but still cannot … -
Error when we use pandas "apply" and "lambda" with Django
We are having a requirement where we need to push a custom code from front end (Django) to back-end (Visual studio code which executes the python code). We are getting the below mentioned error when we use pandas "apply" and "lambda". e.g enter code here exec('''DFrame=pd.DataFrame({'A':['11','2','3'],'B':['X','Y','Z']}) print(DFrame.head()) def DD(X,Y): return X+Y DFrame['C']=DFrame.apply(lambda x: DD(x['A'], x['B']), axis=1) print(DFrame.head())''') Error we are getting : NameError: name 'DD' is not defined Can anyone please suggest a workaround for this? -
remove duplicates data from a queryset in django
I'm working on a Django project and need some help 🙏. I am trying to delet duplicated data from my table, i tried this : for sign in Signal.objects.values_list('signal_name', flat=True).distinct(): Signal.objects.filter(pk__in=Signal.objects.filter(signal_name=sign).values_list('id', flat=True)[1:]).delete() But it deletes all the data from the table, anyone knows what's the problem with my code? -
TypeError: unsupported operand type(s) for ** or pow(): 'bool' and 'dict'
I am using Django, and I am trying to implement user creation using dictionaries parsed from JSON. However I keep getting a type error as is user is not created, but the user is actually created. class SignupView(ReactView): def post(self, request, *args, **kwargs): field_names = ["username", "first_name", "last_name", "email", "password"] try: self.body = json.loads(request.body) except JSONDecodeError: return JsonResponse({"error": "Data must be in JSON"}) except RawPostDataException: return JsonResponse({"error": "Data must be application/json"}) if not any(field in self.body for field in field_names): return JsonResponse({"error": "Missing fields"}) else: try: user = UserModel(**self.body) # Line where I pass body as kwargs user.set_password(self.body.get("password")) user.full_clean() # Will ideally throw TypeError if fields are invalid user.save() return JsonResponse({"success": "User was created"}) except TypeError as err: return JsonResponse( { "error": "unexpected parametes. Allowed parameters are {}".format( field_names ) # THIS RUNS WITH EVERY POST REQUEST I MAKE FOR USER CREATION IF SUCCESSFUL } ) except ValidationError as e: return JsonResponse({"error": str(e)}) How do I alert the caller that the user was created? When an error is received in the caller, a different set of actions is performed. -
Signup form cleaned_data
Hi, i have a custom signup form and i use django localflavors as filed validation for two of the fields. I have build a custom validation and it works, but when i return cleaned data the form skips the validations that comes with my local flavor fields. to sum the problem when i define my own custom clean_data function for validation it overrides the django locolaflavors validation. The form class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name', required=True) last_name = forms.CharField(max_length=30, label='Last Name', required=True) sec_id = SEPersonalIdentityNumberField(max_length=30, label='Pid', required=True) org_nr = SEOrganisationNumberField(max_length=30, label='Org_nr', required=True) telephone = forms.CharField(max_length=20, label='Telephone', required=True) address = forms.CharField(max_length=30, label='Address', required=True) city = forms.CharField(max_length=30, label='City', required=True) zip_code = forms.CharField(max_length=30, label='Zip_code', required=True) state = forms.ChoiceField(choices=COUNTY_CHOICES,label='State', required=True) country = forms.ChoiceField(choices=COUNTRY_LIST,label='Country', required=True) My custom validation def clean(self): """ Clean the form """ cleaned_data = super().clean() secid= self.cleaned_data["sec_id"] if User.objects.filter(profile__sec_id=sec_id).exists(): self.add_error( 'sec_id', _('If you have a account please reset your password'), ) return cleaned_data -
how can I Create Temporary Video File using tempfile in Python
I'm new to Django. I want to post a video in FireBase In Django Using Pyrebase what I want to do is get a video from User store it in tempfile as mp4 then Upload it in firebase and get the URL It Takes All the things from video.html Views.py def video(request): titles = request.POST.get('title') category = request.POST.get('category') with tempfile.NamedTemporaryFile(suffix='.mp4') as f: f.write(request.POST.get('video')) ##I Dont know what is going wrong here random_file_name = 'video'+'-'+str(uuid.uuid4()) storage_ref = firebase.storage.child('trial/randm_file_name') storage_ref.put(f.name) video_url = storage_ref.get_url() with tempfile.NamedTemporaryFile(suffix='.png') as f: f.write(request.POST.get("thumbnail")) random_file_name = 'thumbnail'+'-'+str(uuid.uuid4()) storage_ref = firebase.storage.child('trial/randm_file_name') storage_ref.put(f.name) thumbnail_url = storage_ref.get_url() videoupload(title=titles , category=category , video_url=video_url , thumbnail_url = thumbnail_url).save() return render(request, 'video.html') BUT I"M GETTING THIS ERROR Traceback (most recent call last): File "C:\Mitul\IQLYTIKA\Deploy\withtemplates\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Mitul\IQLYTIKA\Deploy\withtemplates\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Mitul\IQLYTIKA\Deploy\withtemplates\uploadvideo\views.py", line 25, in video f.write(request.POST.get('video')) File "C:\Users\Asus\AppData\Local\Programs\Python\Python39\lib\tempfile.py", line 474, in func_wrapper return func(*args, **kwargs) TypeError: a bytes-like object is required, not 'NoneType' -
Can I track and commit without push?
What I'm trying to do is to version a file without ever pushing it to github, is it something I can do ? Context : For instance, I have a local database for dev (Django) which is SQLite3 which creates a file "db.sqlite3". I don't want this file to be on github, but I'd like to be able to reset it to previous version if I mess with the migrations for example. Maybe they are better ways than git, I'm open to suggestions. Thank you ! -
TypeError at /listing: save() missing 1 required positional argument: 'self'
I'm trying to make an auction site and I'm having an issue changing the bid in the Bids model for a particular Auctionlisting object when POST data is submitted. class Bids(models.Model): minimum_bid = models.DecimalField(max_digits=8, decimal_places=2, null=False) allbids = [] bid = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) allbids.append(bid) numBids = len(allbids) def __str__(self): if self.bid == None: return f"Minimum Bid: ${self.minimum_bid}" else: return f"Highest Bid: ${self.bid}" def save(self, userbid, object): item = self.objects.get(pk=object) item.bid = userbid item.save() Here is my AuctionListing model: class AuctionListing(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=137) category = models.CharField(max_length=10, choices=Category.CHOICES, default="Men") image = models.ImageField(upload_to="media") bid = models.OneToOneField(Bids, on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.category}: {self.title}" Here is how I'm submitting the data in my views: if request.method == "POST": if "userbid" in request.POST: try: userbid = AuctionListing.objects.get(pk = request.GET.get("listing")) userbid.bid = Bids.save(userbid=1000,object=object) userbid.save() except IntegrityError: pass -
Django def _str_(self): return self.fname not working
from django.db import models # Create your models here. class Contact(models.Model): fname = models.CharField(max_length=22) lname = models.CharField(max_length=22) mnumber = models.CharField(max_length=12) eid = models.CharField(max_length=22) date = models.DateField() def _str_(self): return self.fname This is the code, everything is fine, I have already tried everything, no error, still, the def str(self) is not working. Please help me. -
: The term 'git' is not recognized as the name of a cmdlet, function, script file, or operable program.
git : The term 'git' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 git remote add origin https://github.com/rehmat11872/gs9django.git + CategoryInfo : ObjectNotFound: (git:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
i have followed everything from a tutorial but it says unexpected indent on line 6, how can i resolve this [duplicate]
from django.shortcuts import render from .models import Post def post_list_view(request): post_objects = Post.objects.all() context = { 'post_objects' : post_objects } return render(request, "posts/index.html", context) -
how to django template list indexing control
{{ object_list }} # show <img src="{{ object_list.0.photo.url }}"># show object_list[0] {% for i in object_list %} # delete object_list[0] from object_list <img src="{{ i.photo.url }}"> {% endfor %} -
Generate table using raw SQL query and want to use those tables as ORM in Django
table_title = 'transaction_' + username with connection.cursor() as cursor: sql = 'CREATE TABLE ' + table_title + '(id uuid NOT NULL, sql += 'amount numeric(10,2) NOT NULL, sql += 'CONSTRAINT transaction_pkey' + username + ' PRIMARY KEY (id),' cursor.execute(sql) I have create table using this code. Now what I want: I want to use them in the application's admin.py I want show them in Django's admin panel I want to use this table as ORM in views. Is it possible? If yes, then how? -
row count in csv file to database Django
I want to limit the no of rows before importing to db, how I can count the rows of csv file in the following function def user_upload(request): template = "user_upload.html" if request.method == "GET": return render(request, template) try: csv_file = request.FILES['file'] except MultiValueDictKeyError: csv_file = None if csv_file: if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') if csv_file: data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): if len(column) > 10: try: users = User( username=column[0], first_name=column[1], last_name=column[2], email=column[3], add_1=column[4], add_2=column[5], suburb=column[6], city=column[7], state=column[8], postcode=column[9], country=column[10], ) users.set_password('password') users.save() except (IntegrityError, ValueError) as e: return render_to_response('message.html') context = {} return render(request, template, context) else: messages.error(request, 'Please select a valid file!') return redirect('home') The data_set, row count is not giving the right figures, seeking help, thank you -
Disable next button in last imgage in image slider Java script
I'm building an image slider with Java script with next button to toggle between the images. So automatically when reach the last image it begins from the first. I want to disable the next button in last image. or change it with another button like submit or something HTML: <div class="slider"> <!-- fade css --> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 1</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img1.jpg" style="width: 100%; height: 100%;"> </div> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 2</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img2.jpg" style="width: 100%; height: 100%;"> </div> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 3</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img3.jpg" style="width: 100%; height: 100%;"> </div> </div> a class="next" onclick="plusSlides(1)">&#10095;</a> JS: const myslide = document.querySelectorAll('.myslide'), dot = document.querySelectorAll('.dot'); let counter = 1; slidefun(counter); let timer = setInterval(autoSlide, 8000); function autoSlide() { counter += 1; slidefun(counter); } function plusSlides(n) { counter += n; slidefun(counter); resetTimer(); } function currentSlide(n) { counter = n; slidefun(counter); resetTimer(); } function resetTimer() { clearInterval(timer); timer = setInterval(autoSlide, 8000); } function slidefun(n) { let i; for(i = 0;i<myslide.length;i++){ myslide[i].style.display = "none"; } for(i = 0;i<dot.length;i++) { dot[i].className = dot[i].className.replace(' … -
How can I display my in save to create new playlist on side bar in django just like youtube playlist?
The button has now been renamed to "Save," and a single tap will automatically add the video to your most recently selected playlist (or your Watch Later list, if you haven't used the feature before).then my question is how can we display the list on side bar? -
"Attribute error: module "myApp.views" has no attribute symbol " - Django
I'm using django framework for my app backend, I want to use the attribute (fetched using request.get()) from views.py file into another py file into same directory as views.py . I am getting the following two errors. -
Difference between creating custom Django token generator and using the default PasswordResetTokenGenerator
I'm creating a verification email users app, which as the name may suggest verify users' emails before activating their accounts. I've seen in many tutorials that they use the following code to create a custom token generator for account activation: class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return text_type(user.is_active) + text_type(user.pk) + text_type(timestamp) token_generator = TokenGenerator() However, I don't see why I should use this over the default PasswordResetTokenGenerator. I've tried to implement both, the custom and the default and the result is the same. Why do they suggest inheriting PasswordResetTokenGenerator and create an AccountActivationTokenGenerator. Is there any security issue if I use the same token generator for two tasks?