Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF- Got assertion error when I give Post Request
Error AssertionError: The `.create()` method does not support writable dotted-source fields by default. Write an explicit `.create()` method for serializer `hrm_apps.configuration.serializers.CurrencySerializer`, or set `read_only=True` on dotted-source serializer fields. models.py, class CurrencyMaster(models.Model): code = models.CharField(max_length=3, null=False, unique=True) name = models.CharField(max_length=100, null=False, unique=True) def __str__(self): return self.name class Currency(models.Model): currency_master = models.OneToOneField(CurrencyMaster, on_delete=models.RESTRICT) conversion_rate = models.FloatField(null=False) def __str__(self): return self.currency_master.name views.py, class CurrencyViewSet(viewsets.ModelViewSet): queryset = Currency.objects.all() serializer_class = CurrencySerializer lookup_field = 'id' serializers.py, class CurrencySerializer(serializers.ModelSerializer): currency_master = serializers.CharField(source="currency_master.name") class Meta: model = Currency fields = ['id', 'currency_master', 'conversion_rate'] When i give post request i got assertion error like above, class CurrencySerializer(serializers.ModelSerializer): currency_master = serializers.CharField(source="currency_master.name") class Meta: model = Currency fields = ['id', 'currency_master', 'conversion_rate'] def create(self, validated_data): return Currency.objects.create(**validated_data) def update(self, instance, validated_data): instance.currency_master = validated_data.get('currency_master', instance.currency_master) instance.conversion_rate = validated_data.get('conversion_rate', instance.conversion_rate) return instance I tried above i got this error "ValueError: Cannot assign "{'name': 'ALL - Albania Lek'}": "Currency.currency_master" must be a "CurrencyMaster" instance". How to resolve this??? -
inspectdb unrecognized arguments PackageWeight
Is it possible in Django 1.8 to inspect specific table? When I run (according to this): $ python manage.py inspectdb --database=default PackageWeight It writes: usage: manage.py inspectdb [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--database DATABASE] manage.py inspectdb: error: unrecognized arguments: PackageWeight -
Want to save image URL in Python Django
This is my model class MenuOptions(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) This is my form class MenuOptionsForm(forms.ModelForm): class Meta: model = MenuOptions fields = ['name', 'description'] And this is my view if request.method == 'POST': form = MenuOptionsForm(request.POST) if form.is_valid(): form.save() return redirect('menu-options') else: form = MenuOptionsForm() I want to have the image field in the forms only so that I can upload the image on S3/Google storage I know how to do that and after uploading the image to the storage I want to save only the image_url to the DB, not the image. So it can not be an image_filed in the Django model it has to be a string. -
sqlanydb.OperationalError column not found
When I run python manage.py inspectdb it ends with error messsage Traceback (most recent call last): File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/base.py", line 98, in execute ret = self.cursor.execute(trace(query), trace(args)) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 796, in execute self.executemany(operation, [parameters]) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 767, in executemany bind_count = self.api.sqlany_num_params(self.stmt) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 701, in __stmt_get self.handleerror(*self.parent.error()) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 695, in handleerror eh(self.parent, self, errorclass, errorvalue, sqlcode) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 379, in standardErrorHandler raise errorclass(errorvalue,sqlcode) sqlanydb.OperationalError: (b"Column 'a' not found", -143) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/commands/inspectdb.py", line 25, in handle for line in self.handle_inspection(options): File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/commands/inspectdb.py", line 64, in handle_inspection relations = connection.introspection.get_relations(cursor, table_name) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 62, in get_relations my_field_dict = self._name_to_index(cursor, table_name) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 55, in _name_to_index return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))]) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 46, in get_table_description cursor.execute("SELECT FIRST * FROM %s" % File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 62, in … -
rendering form in html django
I have this app and its working but i'm confused whether to use form method or POST.get method. with form i'm getting so many challenges like rendering form on custom html suppose i have this change password screen, for that i need to create form then use this on html template and with custom html it gets more complicated to use form fields. forms.py: class ChangePasswordForm(PasswordChangeForm): old_password = forms.CharField(label="Old Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) new_password1 = forms.CharField(label="New Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) new_password2 = forms.CharField(label="Confirm Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) class Meta: model = User fields = ('old_password', 'new_password1', 'new_password2') views.py: # Password Change View def changePassword(request): if request.method == 'POST': form = ChangePasswordForm(request.user, request.POST) print(form) if form.is_valid(): print("form valid") user = form.save() update_session_auth_hash(request, user) messages.success(request, "Password Changed Successfully") return redirect('changePassword') else: messages.error(request, "Something Went Wrong, Please Try Again ") return redirect('changePassword') else: form = ChangePasswordForm(request.user) return render(request, 'admin/user_auth/change_password.html', { 'form': form }) html: {% extends "admin/layouts/default.html" %} {% load static %} {% block content%} <div class="row"> <div class="col"> <div class="titleBlock"> <a href="{{request.META.HTTP_REFERER|escape}}"><h1><i class="fas fa-chevron-circle-left mr-3"></i>Back</h1></a> </div> <div class="card"> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class=" … -
Django distinct query is still returning duplicates
I have a shopping list which I can fill by adding all the ingredients from a recipe. I want to query Shopping to see get all unique recipes present in a Shopping List, however my distinct query is returning duplicates? #query ShoppingItems.objects.filter(user=account, shoppingList=shoppingList, recipe__isnull=False).values('recipe').distinct() #returns > <ShoppingItemsQuerySet [{'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}]> #shopping/models.py class ShoppingLists(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) class ShoppingItems(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shoppingList = models.ForeignKey(ShoppingLists, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=220, blank=True, null=True) # chicken # recipes.models.py class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # grilled chicken pasta -
How to join like sql in django models
I have these three models which has not contained foreign key class SchoolReg(models.Model): # TODO: Define fields here user = models.ForeignKey('front.User', on_delete= models.CASCADE) fullname = models.CharField(max_length= 100) dob = models.CharField(max_length= 50) class CandidateCode(models.Model): candidateCode = models.IntegerField() regId = models.IntegerField() regCategory = models.CharField(max_length=20) class Sec1(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, blank= True, null = True) centreName = models.CharField(max_length= 50, blank= True, null = True) compRegNo = models.CharField(max_length= 50, blank= True, null = Tru now I want join these models and make a queryset of student like this SELECT * from school_reg s LEFT JOIN sec1 c on s.user_id = c.user_id LEFT JOIN candidate_code cc on cc.reg_id = s.school_id WHERE c.center_name = "centreName" -
Partially Shifting to react from Django
Basically I have a project in Django, in all it has 7 apps. I want to shift one of them in react. Say app 'Student' is the one which I want in React. I want to know if its possible to do so, if yes then how? Here is what I tried, I created a react project and using npm run build command I got a build of that react project. Now for base url of Student i rendered template which was in react build folder. Something like this. urls.py urlpatterns = [ ... ... path('student/', views.Student, name='student'), .... ] views.py def Student(request): return render(request, 'build/index.html') Where index.html is the file present in build folder. Using this approach i was able to render the react template but the other url routes were not working. Please let me know what's wrong in this approach, if this approach is wrong then do suggest another approach. -
How can i make my python with django website be used my many users? for now it only logs in one user at a time
Developed python website with django but i have a challenge, whenever i'm logged in and another user tries to log in he/she is taken to my dashboard(currently logged in user) instead of being asked to log in to his/her account. So my website is like only one person can use at a time, have tried using decorators (@login required) but still facing same problem. What i'm i lacking kindly -
Copy current form data into new form using django
I have two views, PostCreateView and PostUpdateView. They both route through the same html template, post_form.html. I want to create a Copy button that only appears if I am accessing a record through PostUpdateView. Pressing the Copy button will create a new record pre-filled with all the data from record that I was just on. PostCreateView code: class PostCreateView(LoginRequiredMixin, FormView): template_name = 'trucking/post_form.html' form_class = RecordForm def form_valid(self, form): form.instance.author = self.request.user obj = form.save(commit=False) obj.save() messages.success(self.request, f'RECORD: {obj.container_no} was saved') return super().form_valid(form) def get_success_url(self): if self.request.POST.get('Save_Exit'): return reverse('close') elif self.request.POST.get('Save'): return reverse('post-create') else: return reverse('database') PostUpdateView code: class PostUpdateView(LoginRequiredMixin, UpdateView): form_class = RecordForm model = Post def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) history = Post.objects.filter(id = self.object.id).first().history.all().reverse() data['history'] = get_status_changes(history) return data # checks to make sure the user is logged in def form_valid(self, form): form.instance.author = self.request.user obj = form.save(commit=False) messages.success(self.request, f'RECORD: {obj.container_no} was updated') return super().form_valid(form) def get_success_url(self): if self.request.POST.get('Save_Exit'): return reverse('close') # return render(self.request, 'trucking/email_close.html') elif self.request.POST.get('Save'): return reverse('post-update', kwargs={'pk': self.object.id}) else: return reverse('database') Based on this post I tried creating a view like so: def copy(request): post = Post.objects.get(pk = request.users.post.id) my_form = RecordForm(instance = post) return render(request, 'trucking/post_form.html', {'form': my_form}) However, I get an … -
How to filter in django to get each date latest record
Example Record Table id value created_datetime 1 10 2022-01-18 10:00:00 2 11 2022-01-18 10:15:00 3 8 2022-01-18 15:15:00 4 25 2022-01-19 09:00:00 5 16 2022-01-19 12:00:00 6 9 2022-01-20 11:00:00 I want to filter this table 'Record Table' as getting each date latest value.For Example there are three dates 2022-01-18,2022-01-19,2022-01-20 in which latest value of these dates are as follows Latest value of each dates are (Result that iam looking to get) id value created_datetime 3 8 2022-01-18 15:15:00 5 16 2022-01-19 12:00:00 6 9 2022-01-20 11:00:00 So how to filter to recieve results as the above mentioned table -
Multistage docker build for Django
I am dockerizing my Django application with docker multi-stage build. Now am facing an issue with dependencies Dockerfile FROM python:3.8-slim-buster AS base WORKDIR /app RUN python -m venv venv ENV PATH="/app/venv:$PATH" COPY requirements.txt . RUN pip install -r requirements.txt \ && pip install gunicorn COPY entrypoint.sh . COPY . . FROM python:3.8-slim-buster WORKDIR /app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY --from=base /app /app/ ENV PATH="/app/venv:$PATH" ENTRYPOINT sh entrypoint.sh When running the container it raises import error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
login not working in Django after migrating to 3.2 getting error: django.db.utils.ProgrammingError
I recently migrated my Django version from 2.2 to 3.2 and login stopped working after that. In 2.2 it was working fine. It is giving an error:- > Traceback (most recent call last): > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/handlers/exception.py", > line 47, in inner > response = get_response(request) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/handlers/base.py", > line 181, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/generic/base.py", > line 70, in view > return self.dispatch(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/decorators.py", > line 43, in _wrapper > return bound_method(*args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/decorators/debug.py", > line 89, in sensitive_post_parameters_wrapper > return view(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 146, in dispatch > return super(LoginView, self).dispatch(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 74, in dispatch > response = super(RedirectAuthenticatedUserMixin, self).dispatch( > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/generic/base.py", > line 98, in dispatch > return handler(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 102, in post > response = self.form_valid(form) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 159, in form_valid > return form.login(self.request, redirect_url=success_url) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/forms.py", > line 196, in login > ret = perform_login( > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/utils.py", > line 171, in perform_login > if not _has_verified_for_login(user, email) and signup: > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/utils.py", > line 139, in _has_verified_for_login > ret = EmailAddress.objects.filter(user=user, … -
How to display uploaded pdf file along with machine name and operation number based on select from dropdown
In this project, I want to display machine name and operation number along with uploaded pdf files based on select machine name and operation number from dropdown menu. This project is working but when I add and select another file in same machine name and operation number, it is displaying two pdf files along with previous pdf file of another machine name and operation number, exactly I don't want it. It should display machine name and operation number along with uploaded pdf file based on select from dropdown menu. And also when I upload another pdf files in same machine name and operation number, it should display two pdf files along with same machine name and operation number within same row. This project is working fine but I want above validations. Please anyone can help me out, this will be great for me. Please.. views.py: def upload(request): controlmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machinename', '') operation_no = request.POST.get('operationname','') choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no) cmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines,'choiced_cmachine':choiced_cmachine}) def index(request): if request.method == 'POST': form = ControlmachineForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlmachineForm() controlmachiness = Controlmachine.objects.all() return render(request,'usermaster/upload_file.html',{'form':form,'controlmachiness':controlmachiness}) upload.html: … -
Django inspectdb not creating primary keys
When I run python manage.py inspectdb --database totals > modelstest.py it appears to function as expected and I get my models, but it does not create primary keys and add an id field although everything I can find online says it does, little confused. I went into my settings file and added DEFAULT_AUTO_FIELD='django.db.models.AutoField' but now when I try to migrate again there is nothing to migrate, I flushed my db and tried to migrate again but it didn't really do anything, a little confused how I can migrate again to kick in that auto field setting now? -
how to dump postgres database in django running in docker-container?
I have an application running in a docker container and psql database running in a docker container as well. i want to dump database while in django container, i know there is dumpdata in django but this command takes long time, i also tried docker exec pg_dump but inside django container this command doesn't work. services: db_postgres: image: postgres:10.5-alpine restart: always volumes: - pgdata_invivo:/var/lib/postgresql/data/ env_file: - .env django: build: . restart: always volumes: - ./static:/static - ./media:/media ports: - 8000:8000 depends_on: - db_postgres env_file: - .env Is there any way to do pg_dump without using docker exec pg_dump while in django container? -
How can I add certain number of day to a date, with python - timedelta?
I am stuck with an issue. Basically, I have to add, depending on the type of duration, a certain number of days to a date. My model and functions are like that: models.py from django.db import models import datetime # Create your models here. FRAZIONAMENTO = ( ('Annuale', 'Annuale'), ('Semestrale', 'Semestrale'), ('Quadrimestrale', 'Quadrimestrale'), ('Mensile', 'Mensile'), ) class Polizza(models.Model): cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE) numero_polizza = models.CharField(max_length=100) data_decorrenza = models.DateField() data_scadenza = models.DateField(blank=True, null=True) ramo_polizza = models.CharField(max_length=100, choices=RAMO_POLIZZA) polizza_nuova = models.BooleanField(default=True) frazionamento = models.CharField(max_length=100, choices=FRAZIONAMENTO) premio = models.DecimalField(max_digits=5, decimal_places=2) provvigione = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) creata = models.DateTimeField(auto_now_add=True) aggiornata = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Polizza' ordering = ['data_scadenza'] def __str__(self): return self.ramo_polizza + ' ' + self.frazionamento @property def get_data_scadenza(self): if self.frazionamento == 'Annuale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=365)) elif self.frazionamento == 'Semestrale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=180)) elif self.frazionamento == 'Quadrimestrale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=120)) elif self.frazionamento == 'Mensile': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=30)) return data_scadenza def save(self, *args, **kwargs): self.provvigione = self.get_provvigione super(Polizza, self).save(*args, **kwargs) views.py def nuova_polizza(request): clienti = Cliente.objects.all() polizze = Polizza.objects.all() context = { 'clienti': clienti, 'polizze': polizze, } return render(request, 'anagrafica/nuova_polizza.html', context) def salva_nuova_polizza(request): if request.method == 'POST': cliente … -
Show a part of the template that has been previously filtered
I would like to know what is the most pythonic way to get the following result: Let's say we have a view: def myView(request): context = {} if something: context['A'] = "Whatever" else: context['B'] = "Whatever" return render(request, 'mypage.html', context) In the template, let's say mypage.html we have the following scenario: {% if A %} A code {% else %} B code {% endif %} When the page loads, the code is rendered depending on whether we have A or B in the view context. My question is: if the page renders with the A code (for example), is it possible through a button when clicking on that button to hide A code and show B code instead? -
How to connect uploaded pdf file to dropdown list in django
In this project, I want to display uploaded pdf files along with machine name and operation number based on select from dropdown list. Here, when I select machine name and operation number, It is displaying the pdf file but when I select another machine name and operation number, it is displaying two pdf files along with previous pdf file, exactly I don't want this, How to solve this. And also when I add another pdf file in same machine name and operation number, It should display two pdf files within same row. This project is working correctly, but I want above validations. Please anyone solve this for me, that will be great for me. Please views.py: def control_upload(request): if request.method == 'POST': form = ControlForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlForm() controlmachiness = Controlmachine.objects.all() return render(request,'master/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def control_index(request): controlmachines = Controlmachine.objects.all() return render(request,"master/control_show.html",{'controlmachines':controlmachines}) def control_destroy(request, id): controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() return redirect("/") control_show.html: <div class="col-md-12"> <div class="table-responsive"> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%"> <thead> <th><input type="checkbox" id="checkall" /></th> <th>ID</th> <th>Machine Name</th> <th>Operation Number</th> <th>File</th> <th>Delete</th> </thead> <tbody> {% for control in controlmachines %} <tr> <td><input type="checkbox" class="checkthis" /></td> <td>{{ control.id }}</td> <td>{{ control.machine_name }}</td> <td>{{ … -
Filtering out a message for a single user
Inbox = Messages.objects.filter(Q(sender=request.user)&Q(senderDeleted=False) | Q(receiver=request.user)&Q(receiverDeleted=False)).order_by("-time", "read") context['Inbox'] = Inbox unreadMessagesCount = Messages.objects.filter(Q(receiver=request.user) & Q(read=False)&Q(receiverDeleted=False)).count() context['unreadMessagesCount'] = unreadMessagesCount I am trying to filter out messages by who doesn't want them to be seen anymore. The logic goes if senderDeleted or receiverDeleted is True then don't let the messages appear anymore. Currently the messages stay on the page unless they both click delete or the message sender being deleted is the current user logged in. What I'd like for it to do is remove it from the view of a single user and allow the other user to still view it. When clicking on the elements it does switch the fields to the True value as well. @login_required @require_http_methods(["POST"]) def delete(request,messageID): #Only remove the message if both people want it removed or if the send and receiver are the same person data_to_be_deleted = Messages.objects.get(id = messageID) if data_to_be_deleted.sender == data_to_be_deleted.receiver: data_to_be_deleted.delete() return redirect('messagesInbox') else: if data_to_be_deleted.sender==request.user: data_to_be_deleted.senderDeleted=True data_to_be_deleted.save() else: data_to_be_deleted.receiverDeleted=True data_to_be_deleted.save() data_to_be_deleted = Messages.objects.get(id = messageID) if data_to_be_deleted.senderDeleted and data_to_be_deleted.receiverDeleted: data_to_be_deleted.delete() return redirect('messagesInbox') models.py: class Messages(models.Model): sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE) senderDeleted = models.BooleanField(default=False) receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE) receiverDeleted = models.BooleanField(default=False) subject = models.CharField(default='',max_length=100) text = models.CharField(default='',max_length=4096) time = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) parent = … -
How do you setup your .venv environment?
I have a few basic questions regarding Virtualenv. I can install it, I can run it, activate it, all of this is good. My question is "And then what ?" How do setup your dev env ? -Do you create a new .venv for each project ? -And within that each project having its specific modules ? -Modules which are not used (for any reason, try a few, keep one, for instance) how are they removed ? -Going this way, once your project is finished and delivered, or dropped for any reason, how do you uninstall its .venv ? I did read the docs, it's mainly about installation, examples, coding and so on. What I can't figure is a proper usage of this tool. Thanks in advance for your help -
How to use jQuery to make a Django Alert appear (sliding down)
The following script is working fine to fade out my Django alert: <script> $(document).ready(function(){ window.setTimeout(function() { $(".alert").fadeTo(500, 0).slideUp(500, function(){ $(this).remove(); }); }, 2000); }); </script> But the following is not working---I'm just trying to do the opposite here: make the Django alert appear by sliding down. How can I make the below work? <script> $(document).ready(function(){ $(".alert").show().slideDown(500, function(){ }); }); </script> -
Django web page shows error when running server
I have just started a Django project and spun up a web server. I have made minimal changes which I will post below. When I start my server, I am given a url which I click on to navigate to my web app. I see the following error I am running python manage.py runserver to run my server Following are the only changes I have made to the files: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', ] urls.py from django.urls import path from .views import HomePageView urlpatterns = [ path('', HomePageView, name='home'), ] urls.py in the project folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')) ] views.py from http.client import HTTPResponse from django.http import HttpResponse def HomePageView(request): return HTTPResponse("Hello Django") -
Logging in django is not outputting anything
I was having issues with print statements and Django and I saw on here that its better to do logging. I am not sure what I am doing wrong though. It logs sometimes to console and other times it doesn't for the same page and I cant get it to log anything in my post method. I have tried doing the ```logger = logging.getLogger("mylogger") above all the class views, ive tried adding that line to each individual method and ive tried only having it in 1 at a time. Any thoughts? Settings.py Logger Settings LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'filters': ['require_debug_true'], }, }, 'loggers': { 'mylogger': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), 'propagate': True, }, }, } Views.py class CreateOrderView(View): def get(self, request,): logger = logging.getLogger("mylogger") logger.info("TEST") # this should be removed once user_ids are implemented through login system and session creation request.session["user_id"] = 1 # should be set to session.get("user_id") probably in the future user_id = request.session.get("user_id") trade_form = CreateTradeForm() order_form = CreateOrderForm() context = {} context["user_id"] = user_id context["order_form"] = order_form context["trade_form"] = trade_form return render(request, "trading_log/add-order.html", context) def post(self, request): trade_form … -
Unable to return using post method in an html form. what am i doing wrong?
I am new to programming, i have been learning django for the first time. I created a form using home.html file an i requested using POST method, but in the error it is giving the request method as GET. When I remove the method="POST" and put request.GET in views file, it is working fine. What am I doing wrong here? home.html < form action="add" method="POST"> {% csrf_token %} Enter 1st number : <input type="text" name="num1"><br> Enter 2nd number : <input type="text" name="num2"><br> <input type="submit"> views.py def add(request): val1= int(request.POST['num1']) val2= int(request.POST['num2']) res= val1 +val2 return render(request, 'result.html' ,{'result': res}) I am getting the following error: MultiValueDictKeyError at /add 'num1' Request Method: GET Request URL: http://127.0.0.1:8000/add?num1=17&num2=4 Django Version: 4.0.1 Exception Type: MultiValueDictKeyError Exception Value: 'num1'