Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configuring a django app and it's options on loading
I have a stupid yet intriguing situation in which I need to reload one of my Django Apps as the user changes some stuff in it's configuartion. To make stuff more clear for you helpers, I have made a ready function that loads some of it's components from a YAML file, then, with the help of some views, the user changes this YAML file, and long story short I want the app to reload it's self with that newly configuration options, here is some code.. # apps.py file def read_yaml(): path = os.path.join(os.getcwd(),'config.yaml') with open(path) as f: conf = yaml.safe_load(f) return conf class ActivateanduseConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'activateAndUse' def ready(self): """ A ready function to make stuff load on startup """ config = read_yaml() self.option1 = SomeClassOrFunction(config["config"]["model_ref_url"]) ================ # views.py file class SelectConfigStuff(APIView): """ API VIEW TO CHANGE Some OPtions """ def post(self, request, format=None): """ In the request we only expect the model ref name to be specified """ newlyOptzzz = request.data.get("newOpts") new_yaml_data_dict = { "option": newlyOptzzz , } with open('config.yaml','r') as yamlfile: cur_yaml = yaml.safe_load(yamlfile) cur_yaml['config'].update(new_yaml_data_dict) with open('bugs.yaml','w') as yamlfile: yaml.safe_dump(cur_yaml, yamlfile) return Response(data={"message":"done ! "}, status=201) Now the code above only changes to startup options … -
converting html code to java script string format
I am having html code for hyperlink as below: <td> <a href="{% url 'select_stock_report' book.id %}">{{ book.code }}</a></td> <td>{{book.name}}</td> it is directing to the correct page. In Script from the response I update the page as below It is not giving error (of course link page is empty because of 1 as parameter): html += "<tr> <td> <a href= '{% url 'select_stock_report' 1 %}'>"+item1.code+"</a></td>"+ "<td>" + item1.name + "</td>" + "<td>" + item1.open_qty + " </td>" But I want to replace 1 (one) with item1.id. html += "<tr><td><a href='{% url 'select_stock_report' item1.id %}'>"+item1.code+"</a></td>"+ "<td>" + item1.name + "</td>" + "<td>" + item1.open_qty + " </td>" But I am getting error. How to build the line with this replacement. I tried all "",'',+ with this item.id without success. Thanks for your help. -
Django admin TabularInLine on non-direct relation betwin model
my models : class Oeuvre(models.Model): user = models.ForeignKey(BaseUser, on_delete=models.CASCADE) title = models.CharField(max_length=255) [...] class BaseUser(AbstractUser): """User model.""" username = None email = models.EmailField(_("email address"), unique=True) [...] class UserProfile(models.Model): user = models.OneToOneField( BaseUser, primary_key=True, on_delete=models.CASCADE) [...] my admin.py class OeuvreInLine(admin.TabularInline): model = Oeuvre extra = 0 show_change_link = True this result to : tabular in line for instance of BasUser model i want the same thing but in an instance of user profile, i have already tried TabularInLine and StackInLine. thx in advence ! -
Django Model: How to only access fields related to a specific user from another model
How can i only access the addresses(Address model) of specified user(User model) from Order model. here is the code: Models.py class User(AbstractBaseUser, PermissionsMixin): phone_number = PhoneField(max_length=12, primary_key=True, unique=True) class Address(models.Model): address = models.CharField(max_length=500, blank=False,null=False,primary_key=True) customer = models.ForeignKey((User, on_delete= models.CASCADE) class Order(models.Model): order = CharField(max_length=400,blank=False,null=False) customer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address,on_delete=models.SET_NULL, null=True) the address field in Order model is my problem. When creating a new order in Django Administration, when i select one of the customers, i still can choose any address registered in database How can i limit the access to addresses to specified user. Thanks in advance -
Search list JSONField postgres Django
I have a JSONField which is an empty list ([]) by default. The data stored in the field is as follows: [{"operand":"key1","value":"value1"},{"operand":"key2","value":"value2"} and so on....] Now I want to search this JSONField and return the result if the search query is present in the values of either "operand" or "value". So for example is search query comes as "value", "value1", "key", "key2", the above mentioned record should be returned. So how to implement it in Django? -
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?