Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Null Integrity error not allowing POST
The error that I am getting when trying to POST is: django.db.utils.IntegrityError: null value in column "interest_category_id" of relation "teamStart_project" violates not-null constraint Here are my Serializers: class InterestSerializer(serializers.ModelSerializer): class Meta: model = Interests fields = ('id', 'interest_name') class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project fields = ( 'project_title', 'project_description', 'interest_category', 'created_at', 'updated_at', ) Here are my models: class Interests(models.Model): interest_name = models.CharField(max_length=50) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.interest_name class Project(models.Model): project_title = models.CharField(max_length=255) project_description = models.TextField(max_length=1500) interest_category = models.ForeignKey(Interests, on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='projects', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Project name:" + "\n" + self.project_title + "\n" + "|" + "\n" + "Created By:" + "\n" + self.created_by.username I can get rid of the error by removing interest_category = serializers.StringRelatedField() but this issue is, if I do not remove this line, the frontend shows the ID of interest_category and not the respective name. For example, this is what the frontend will show: With this line: interest_category = serializers.StringRelatedField() -------------------------------------------------------------------- Project Title: TestItem1 Project Description: TestItem1Desc Interest Category: Django Without the line: --------------------------------------------------------------------- Project Title: TestItem1 Project Description: TestItem1Desc Interest Category: 1 When I … -
django - swap foreign keys of one-to-one relationship in an atomic transaction
i have a Unit model with a one-to-one related handler defined as such: handler = models.OneToOneField('users.Handler', related_name="unit_obj", blank=True, null=True, on_delete=models.SET_NULL) i'm trying to update a set of units in an atomic transaction where the unit's handler_id foreign key can be set to null or any other handler_id. the problem is when handlers are being swapped. i initially tried saving the updated unit inside an atomic transaction. but as soon as unit.save() is called on the first unit i get an integrity error because the second unit still has the same handler_id. i was hoping that the atomic transaction would defer the integrity error on individual unit.save() calls and only throw the error at the end of the transaction if there actually were any. try: with transaction.atomic(): for unit_model in unit_models: unit = Unit.objects.get(id=unit_model['id']) unit.handler_id = unit_model['handler']['id'] if unit_model['handler'] is not None else None unit.save() except IntegrityError as e: print(f'Error saving units: {str(e)}') then i tried using bulk_update which i was sure would solve the issue. unfortunately i get the same error (duplicate key value violates unique constraint) even though i have confirmed that there are no duplicates in the list. it still seems to be applying the saves sequentially, though … -
Django Testing for Login and token collection
Trying to write test for Django login. I want to request to login, collect token and access different view functions. How do i write a test in python for this. Help appreciated. -
connect to a postgres database inside of a docker container from django running on host machine
I have a postgres database running inside a container with pgadmin connected to it, the docker-compose.yml is as follows: postgres: image: postgres:13.0-alpine volumes: - postgres:/var/lib/postgresql/data ports: - "5432:5432" env_file: - $ENV_FILE pgadmin: image: dpage/pgadmin4 volumes: - pgadmin:/var/lib/pgadmin ports: - "${PGADMIN_PORT:-5050}:80" restart: unless-stopped depends_on: - postgres env_file: - $ENV_FILE my django database settings are: DATABASES = { "default": { "ENGINE": os.environ.get("POSTGRES_ENGINE", "django.db.backends.postgresql"), "NAME": os.environ.get("POSTGRES_NAME", "postgres"), "USER": os.environ.get("POSTGRES_USER", "admin"), "PASSWORD": os.environ.get("POSTGRES_PASS", "admin"), "HOST": os.environ.get("POSTGRES_HOST", "127.0.0.1"), "PORT": os.environ.get("POSTGRES_PORT", "5432"), } } The traceback is: Traceback (most recent call last): File "C:\Users\liam.obrien\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\liam.obrien\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\channels\management\commands\runserver.py", line 76, in inner_run self.check_migrations() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\core\management\base.py", line 576, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\backends\base\base.py", line 284, in cursor return self._cursor() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\backends\base\base.py", line 260, in _cursor self.ensure_connection() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, … -
Can i use doument.cookie to edit a cookie created with request.set_cookie in django project?
I am working on a Django project. Basically a simple game that uses x and y cordinates to determine the pos of the player on the map using js. So i figured that using cookies to "save" the progress of the player would be a simple way for what i need. Since i need to get these parameters from javascript file i was wondering if i could edit them directly from the file without the need of using a json to pass them to the views.py in order to check if the cookie is empty or has data when the user selects either load game or start a new one. I prefer doing it this way if possible to be able to maintain cookies without expiring thanks to django sessions engine since i haven't found a way to pass the data directly between the views.py and the .js files. Thanks for the help anyway -
How to edit many to many relation different ways in Django admin
Models Movie(models.Model): categories = ManyToManyField('Category', blank=True) Category(models.Model): grouping = CharField(choices=CategoryGroupings) where CategoryGroupings is one of 'genre', 'holiday', or 'custom' Question In the Movie Django admin, I would like to have three autocomplete_fields, one for each of the individual category types. I can't add 'categories' three times to the autocomplete_fields array. Without altering the model field definitions (ie without needing a migration), how would I manage this? -
How to pass extra argument to get_serializer_class
I need to select a serializer based on the value of an object instance. How do I pass an additional argument to get_serializer_class to be able to do the validation there? def get_serializer_class(self, extra_option): if extra_option: return ModelSerializer return ModelSerializer2 serializer = self.serializer_class(data=request.data, extra_option=smth_instance) Error: TypeError: Field.__init__() got an unexpected keyword argument 'extra_option' -
How to add filters to jQuery.fancyTable (or alternative)
I'm currently using fancyTable to display a table of django results. I have been able to add a search bar and sortable columns (ascending/descending). I've also added "filters" but all they really do is update the search bar with pre-defined text The problem is that I want to be able to use these filters to only show text that matches exactly. For example, if I'm trying to filter by Stage looking for Prescreen I will currently get lines that include Prescreen, Passed - Prescreen 1, and Passed - Prescreen 2 I've already tried writing a function that sets the tr = display="none", but the pagination does not refresh, so I'm left with several blank pages. t Currently initiating fancyTable as such: <script type="text/javascript"> $(document).ready(function () { $(".sampleTable").fancyTable({ /* Column number for initial sorting*/ sortColumn: 0, sortOrder: 'descending', // Valid values are 'desc', 'descending', 'asc', 'ascending', -1 (descending) and 1 (ascending) /* Setting pagination or enabling */ pagination: true, /* Rows per page kept for display */ perPage: 12, globalSearch: true }); }); </script> Any ideas on how I can create these filters? I don't see anything from fancyTable about filters. -
How to implement the onselect event on htmx?
I'm a django developer and I'm new to htmx. I was wondering if there was an easy way to implement the onselect event in htmx. I have the following dropdown: When the role is selected "onselect", I want to send an http request to the back-end using htmx(not jquery or javascript) How can I do this? Any help is much appreciated! Thanks! Tried searching "onselect" on htmx docs but there's no built in implementation. Tried searching "onselect htmx" stack overflow but I couldn't find a helpful post. -
Django find all rows matching 2 columns criteria
Imagine the model Event like this name email A u1@example.org B u1@example.org B u1@example.org C u2@example.org B u3@example.org B u3@example.org A u4@example.org B u4@example.org I would like to find all emails that contains name A and B. In the example ["u1@example.org", "u4@example.org"] Today I'm doing emails = [ e["email"] for e in models.Event.objects.filter(name__in=["A", "B"]) .values("email") .annotate(count=Count("id")) .order_by() .filter(count__gt=1) ] It's not working because I'm also getting duplicates of emails containing only one name (like u3@example.org). -
How I get data from a Input to run a function in Django
i following a django tutorial and i have troubles getting the data from a input in my HTML. This is the code from the tutorial: views.py def buscar(request): if request.GET["prd"]: producto = request.GET["prd"] articulo = Escucha.objects.filter(user__icontains=producto) return render(request, "Producto/resultados_busqueda.html", {"articulo": articulo, "query": producto}) else: mensaje = "Nos has introducido nada" return HttpResponse(mensaje) HTML: <html lang="en"> <head> <title>Busqueda de producto</title> </head> <body> <form action="/buscar/" method="get"> <input type="text" name="prd"> <input type="submit" value="Buscar"> </form> </body> </html> And this is the code I try to run: views.py def suma(request): if request.get["first"]: first = request.GET["Primer"] second = request.GET["Segundo"] variable = first + second return render(request, "resultado.html", {"variable": variable}) else: mensaje = "lo siento" return HttpResponse(mensaje) HTML (pruebas.HTML) <html lang="en"> <head> <title>Document</title> </head> <body> <form action="/pruebas/" method="get"> <input type="text" name="first"> <input type="text" name="second"> <input type="submit" value="suma"> <p>Resultado: {{ variable }}</p> </form> </body> </html> And the problem I get is: AttributeError at /pruebas/ 'WSGIRequest' object has no attribute 'get' Y really don't know what's the problem, for me the two codes are similar. -
How to get rid of redundant requests ord django
class Post(models.Model): cat_post = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True) top_post = models.ForeignKey(TopicsCategory, on_delete=models.CASCADE, blank=True,null=True) sub_post = models.ForeignKey(SubTopicsCategory, on_delete=models.CASCADE, blank=True,null=True) class CreatePostView(CreateView): model = Post template_name = 'blog/create.html' form_class = CreatePostForm def get_context_data(self, *args, **kwards): print(self.kwargs) context = super(CreatePostView, self).get_context_data(**kwards) context['btn'] = 'Add' return context def form_valid(self, form, *args, **kwargs): if self.kwargs.get('category_slug') and len(self.kwargs) == 1: category = Category.objects.get(slug=self.kwargs['category_slug']) form.instance.cat_post = category return super(CreatePostView, self).form_valid(form) # передача в форму kwargs view def get_form_kwargs(self): kwargs = super(CreatePostView, self).get_form_kwargs() kwargs.update({'view_kwargs': self.kwargs}) return kwargs def get_success_url(self): return reverse('topics_category_list', kwargs={'category_slug': self.kwargs['category_slug'], }) class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['name', 'text', 'discussion'] # widgets = { # 'cat_post': forms.HiddenInput(), # } def __init__(self, *args, **kwargs): self.request = kwargs.pop("view_kwargs") super(CreatePostForm, self).__init__(*args, **kwargs) def clean_name(self): name = self.cleaned_data['name'] if self.request.get('category_slug') and len(self.request) == 1: category = Category.objects.get(slug=self.request['category_slug']) unique = Post.objects.filter(slug=slugify(self.cleaned_data['name']), cat_post=category.pk,discussion=False).exists() if unique: raise ValidationError(f'Post is not unique') return name ** I have duplicate sources in db here form_valid and clean_name. How do I pass the form in the view form form_valid class instance that I got from the database to clean_name. There will be posts for 2 models and requests will increase -
Django vacancy calendar issue
I have a problem with my application. I want to add an employee's vacation date in my calendar but when I put the date it only displays the first date (See photo 1). I would like the employee to post every day. In my example I added from Nov 9 to Nov 12. Does anyone have a solution ? ------- Models.p ------- class Conger(models.Model): employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL) Type = models.CharField(max_length=40, null=True) Annee = models.PositiveIntegerField(null=True) Date = models.DateField("Du: (jj/mm/aaaa)", auto_now_add=False, auto_now=False, blank=True, null=True) Date2 = models.DateField("Au: (jj/mm/aaaa)", auto_now_add=False, auto_now=False, blank=True, null=True) Raison = models.CharField(max_length=200, null=True) Superviseur = models.CharField(max_length=60, null=True) Approuver = models.BooleanField(default=False) data_created = models.DateTimeField(auto_now_add=True, null=True) @property def get_html_url(self): url = reverse('conger') return f'<a href="{url}"> {self.employe.Prenom, self.employe.Nom} </a>' ------- utils.py ------- class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(Date__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, … -
Unable to see table of database added in Django Admin portal
relation "dms_mydocs" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "dms_mydocs" enter image description here I did 'python manage.py makemigrations and migrate and still get same error -
Django / Python: Sorting QuerySet by field on first instance of foreignkey relation
I have the following 2 models, a Lesson model, that can have multiple start / end dates - each with their own Date model. class Lesson(models.Model): name = models.Charfield() (...) class Date(models.Model): meeting = models.ForeignKey( Lesson, verbose_name="dates", on_delete=models.CASCADE, ) start_date = models.DateTimeField( blank=True, null=True, ) end_date = models.DateTimeField( blank=True, null=True, ) For our project we need to order the Lessons by the start_date of their earliest Date instance. So far example, if I have the following data: MEETING A: DATE_1a: 2022-11-01 --> 2022-11-02 DATE_2a: 2022-12-10 --> 2022-12-11 MEETING B: DATE_1b: 2022-11-03 --> 2022-11-04 DATE_2b: 2022-11-05 --> 2022-11-06 Then the queryset should return [<MEETING A>, <MEETING B>] based on the start_date values of the DATE_1a/b instances. (2022-11-01 is earlier than 2022-11-03, al other Dates are ignored) However, what I thought would be a relatively simply query has proven to be a rather evasive problem. My initial approach of the default order_by method used all Date instances attached to a Meeting (and worse, returned a separate Meeting result for each Date instance) qs.order_by(F("dates__start_date").asc(nulls_first=True)) However -I could not conceive of a query to do what we need to happen. My current working solution is to use a whole bunch of python code to … -
Django displaying a static image through a variable from models that is in a JSON object
I have been trying to display an image using Django in my HTML. Normally do display a static file somebody would do: <img src="{% static 'user_profile_pics/pfp_2.jpg' %}" > This image static file has been stored in the variable picture in my models.py. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) picture = models.TextField(max_length=500) The user selects the image they want to choose as their profile image. The views.py file is below with the profile definition having the request JSON dictionary with the variable picture being assigned to the model profile.picture. @login_required def profile(request): profile = Profile.objects.get(user = request.user) return render (request, "profile.html", {"userinfo": {'bio': profile.bio, 'picture': profile.picture}}) def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] bio = request.POST['bio'] picture = request.POST['picture'] if password==confirm_password: if User.objects.filter(username=username).exists(): messages.info(request, 'Username is already taken') return redirect(register) elif User.objects.filter(email=email).exists(): messages.info(request, 'Email is already taken') return redirect(register) else: user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) user.save() profile = Profile(bio=bio, picture=picture, user=user) profile.save() return redirect('login_user') else: messages.info(request, 'Both passwords are not matching') return redirect(register) else: return render(request, 'registration.html') Next up, displaying the bio and picture within the profile html … -
How to include the JSON Schema definition of a JSONField inside the OpenAPI schema generated by drf-spectacular?
By default, when using drf-spectacular to generate the OpenAPI schema, the JSONField will be typed as object or array. However, I have a JSON Field which is validated against a JSON Schema and I'd like this JSON Schema to be included on the OpenAPI schema. I couldn't find this specific scenario described on the docs of drf-spectacular, but however, I tried modifying it using @extend_schema but with no success. The model looks like this: Car(models.Model): name = models.CharField() data = models.JSONField("Car Data", validators=[JSONSchemaValidator(limit_value=my_schema)]) On the generated OpenAPI schema, this is represented as: data: type: object additionalProperties: {} nullable: true title: Car Data I'm not including a sample on how it should look because I'm seeking answers where this is possible in some pre-defined way. -
base.html only showing the context data in the home page
I have a ListView for my homepage that displays extra data using the get_context_data method. It works, but only in the url of the HomeView, the homepage, not in other templates after I extend the base.html file. Everything else in base appears, the only thing that doesn't is the context data. HomeView class HomeView(ListView): model = Product context_object_name='products' template_name = 'main/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) news = News.objects.all() ... context.update({ 'news' : news, ... }) return context base.html {% load static %} <body> <div class="navbar"> <a id="title" href="{% url 'home' %}">home</a> </div> ... <div class="side-bar"> <div class="article"> <h3>News</h3> {% for new in news %} <p>{{ new.title }}</p> {% endfor %} <a href="{% url 'news' %}"><p>See more</p></a> </div> </div> {% block content %}{% endblock %} ... </body> home.html {% extends 'main/base.html' %} {% block content %} <div> {% for product in products %} <p>Some text..</p> {% endfor %} {% endblock content %} Does this mean that I have to add a get_context_data method to every single view I have? Isn't that too repetitive and hard to change? -
Django models relation
The idea is that there are two models: Group and Player. My objective is that there are different Groups and each group has players. Each player can belong to one or more groups. Inside a group, each player has some points accumulated, but the same player can have different points accumulated in another group. class Player(models.Model): username = models.CharField(max_length = 200) won_games = models.IntegerField(default=0) class Point(models.Model): player = models.ForeignKey(Player, on_delete=models.PROTECT, related_name='points') val = models.IntegerField() group = models.ForeignKey(Group, on_delete=models.PROTECT, related_name='points') class Group(models.Model): id = models.CharField(max_length = 200) players = models.ManyToManyField(Player,related_name="groups") points = models.ManyToManyField(Point) I am confused because I don't know how to make that a player has "x" points in group A (for example) and also has "y" points in group B. I want to be able to show the data of a group, for each group, show its members and their points. -
Django with docker compose can not open file '/code/manage.py
i am deploying to docker compose django with postgrest but the problem i have is when trying to deploy an app to django as i get the following output. [+] Running 1/0 ⠿ Container proyecto-db-1 Running 0.0s python: can't open file '/code/manage.py': [Errno 2] No such file or directory asterisk@localhost:~/Documentos/Programacion/django/Proyecto> I get this output by implementing the following code: docker compose run web python manage.py startapp aplicacion docker compose run web django-admin startproject proyecto the docker-compose.yml is: version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db The Dockerfile is: # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ requirements.txt: Django>=3.0,<4.0 djangorestframework==3.13.1 psycopg2>=2.8 and .env is: ## do not put this file under version control! SECRET_KEY='c_r-e8v1divj8y+hu@-w=n#$xj#ciuejybd3_(k2h789(mcv8$' DEBUG=False ## Super-User Credentials SUPER_USER_NAME = 'root' SUPER_USER_PASSWORD = 'root' SUPER_USER_EMAIL = 'admin@email.com' -
Setting an initial value of an extra field on a ModelForm from an UpdateView
I have a form which is a modelform with two extra fields. In my model, it includes a PointField which is made up of an easting and northing (the X & Y components of the Point). On my modelform, I do not display the PointField and instead display two DecimalFields for the easting and northing: class QuoteForm(forms.ModelForm): easting = forms.DecimalField() northing = forms.DecimalField() class Meta: model = Quote fields = ('desc', 'client', 'contact', 'amount', 'easting', 'northing', 'note') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['note'].required = True self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Save Quote') ) For my CreateView I include a form_valid that takes the easting and northing and turns them into a point and updates the PointField record. For my UpdateView, I want to go backwards from the PointField and populate the Easting and Northing DecimalFields on my form. I am stuck on how to "pass" this information to my form. I tried a get_form in my UpdateView like this, but it fails: class QuoteUpdateView(PermissionRequiredMixin, UpdateView): permission_required = 'jobs.update_quote' redirect_field_name = 'dashboard' model = Quote form_class = QuoteForm template_name = "jobs/quote_form.html" template_name_suffix = '_form' def get_form(self, form_class=None): form = super().get_form(form_class) quote = self.object pt = quote.ptgeom pt.transform(2953) form.fields['easting'] … -
How do I redirect to the created page after I submitted the form Django
I'm trying to redirect to the created page after I've filled out and submitted a form. I have gotten it to work on the update form but not the create form. How do i do this? Here's what I have so far. Let me know if you need more details and code views.py @login_required(login_url='login') def createRoom(request): form = RoomForm() topics = Topic.objects.all() if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) Room.objects.create( host=request.user, topic=topic, name=request.POST.get('name'), assigned=request.user, status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) return render('room', pk=room.id) context = {'form': form, 'topics': topics, 'room': room} return render(request, 'room/room_form.html', context) But this throws this error traceback Traceback (most recent call last): File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\mikha\issuetracker\base\views.py", line 68, in createRoom return render('room', pk=room.id) Exception Type: AttributeError at /create-room/ Exception Value: 'function' object has no attribute 'id' -
Join two queryset in Django ORM
I'm writing a view that returns this: [ { "field_id" : 1, "stock" : [ { "size" : "M", "total" : 3 } ], "reserved" : [ { "size" : "M", "total" : 1 } ] }, { "field_id" : 2, "stock" : [ { "size" : "M", "total" : 2 }, { "size" : "PP", "total" : 2 } ], "reserved" : [ { "size" : "PP", "total" : 1 }, { "size" : "M", "total" : 2 } ] } ] For this result, I used values and annotation(django orm): reserved = Reserved.objects.all().values("size").annotate(total=Count("size")).order_by("total") stock = Stock.objects.filter(amount=0).values('size').annotate(total=Count('size')).order_by('total')) It's ok for me, but I would like put the reserved queryset inside stock. Like this: [ { "field_id" : 1, "stock" : [ { "size" : "M", "total" : 3, "reserved": 1 } ], }, { "field_id" : 2, "stock" : [ { "size" : "M", "total" : 2, "reserved": 1 }, { "size" : "PP", "total" : 2, "reserved": 0 } ], } ] It's possibile? Reserved and Stock doesn't relationship. -
AAC/ADTS to WAV in Flutter/Django
My Team and I are building a speech-to-text application for a specific purpose. The frontend is in Flutter and the backend is in Django I am using the flutter_sound package for Flutter and the only Codec it supports for recording audio is Codec.aacADTS and I am able to save the file using .aac or .adts On the backend (Django), we're using the Speech Recognition Library and when using the .aac or .adts file with this, it gives an error: ValueError("Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format") We tried using another .wav file and speech recognition works. So, do I need to convert the .aac/.adts file to a .wav file? How should I do it, and should it be on the frontend or the backend? Any library/code snippets to help me with that? Frontend Code (Flutter) Future startRecord() async { setState(() { isRecording = true; }); Directory? dir = await getExternalStorageDirectory(); await recorder.startRecorder( toFile: "${dir!.path}/audio.aac", codec: Codec.aacADTS); } Future stopRecorder() async { final filePath = await recorder.stopRecorder(); final file = File(filePath!); uploadAudio(file); print('Recorded file path: $filePath'); setState(() { isRecording = false; audioFile = file; }); } … -
django - different save methods for user actions and admin action
I have some items connected to users. When every item is added, timestamp is created through inheritance of BaseModel on auto_now field. By mistake when i added new field and populated i updated timestamps. I resolved timestamps with some custom migrations and copy data methods in django. What i wonder - is there possibility to override save method on admin to do only update_fields (so in other words with that i would not update update_at timestamp), while on user actions i want to retain original django save method which would update timestamp. So basically is it possible to have two different save methods? I know that i can override save method - but i don't know if i can have two save methods at the same time.