Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Celery and Sequential Asynchronous tasks
I am building a system in Django that uses Celery and Django-Celery-Beat to run data creation and extraction tasks. I am pulling records from a datastore using it's API and from this creating multiple jsonl files as the final output - these files become the basis for all the subsequent tasks. Then images are made using information from the jsonl files and then these files are used to update other systems (namely Solr). All this works fine. It's the Celery part that has me stummped. These tasks need to be run sequentially and they each can't fail, and if they do the sequence needs to stop. I also need to lock the tasks from running twice as this will mess up the jsonl files, image creation, etc.... What I have looked into is using Celery and chains with immutable signatures, as the tasks don't return anything, they create files, images, etc.... But I can't seem to find a method to lock the tasks from running twice at the same time. So the questions has two parts What is the best method for running periodic tasks in Django that needs to run asynchronously but also sequentially within that task? Is Celery … -
Customizing inlineformset choice in Django template
I've got some forms I'm trying to customize. I render the fields manually - and it all works fine until get to a particular field (which is an InlineFormset itself). I'm trying to customize those options but can't seem to figure out how to do so. my forms.py looks like this: class SummativeScoreForm(forms.ModelForm): subdomain_proficiency_level = forms.ModelChoiceField( empty_label="Undecided", queryset=SubdomainProficiencyLevel.objects.none(), widget=forms.RadioSelect, required=False, ) def __init__(self, request, *args, **kwargs): super(SummativeScoreForm, self).__init__(*args, **kwargs) if self.instance: if request.user == self.instance.summative.employee: self.fields["subdomain_proficiency_level"].disabled = True self.fields[ "subdomain_proficiency_level" ].queryset = SubdomainProficiencyLevel.objects.filter( subdomain=self.instance.subdomain ) self.fields[ "subdomain_proficiency_level" ].label = f""" {self.instance.subdomain.character_code}: {self.instance.subdomain.short_description} """ class Meta: model = SummativeScore fields = "__all__" SummativeScoreInlineFormset = inlineformset_factory( Summative, SummativeScore, fields=("subdomain_proficiency_level",), can_delete=False, extra=0, form=SummativeScoreForm, ) My template for summative_score_form looks like this: <form method="post" novalidate> {% csrf_token %} {% include "myapp/includes/summative_score_response_formset_snippet.html" with formset=form %} <button type="submit" class="btn btn-primary"><i class="fal fa-clipboard-check"></i> Submit Updated Scores</button> </form> The summative_score_response_formset_snippet looks like this: {{ formset.management_form }} {% for formset_form in formset.forms %} {% if formset_form.non_field_errors %} <ul> {% for error in formset_form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} {% for hidden_field in formset_form.hidden_fields %} {% if hidden_field.errors %} <ul> {% for error in hidden_field.errors %} <li> (Hidden field {{ hidden_field.name }}) {{ error … -
Django rest don't see json data of GET XmlHTTPRequest
Recently, i have started playing with django rest framework, my goal is to perform a GET on a rest api with some kind of filtering. For this i have choose to pass filters params as json object. I do this with xmlhttprequest. The problem is the django side don't see my json data when i dump the request. I have try this method with curl and it is ok. But from code, it is not. I have dumped the http headers and see that the only valuable diff is that Content-Length is not set with xmlhttprequest, contrary to curl. I have tried to set it manually but it is refused by javascript engine, he say 'Refuse to set dangerous header', after digging into the internet, this look to be forbidden. I have tried to change to the POST method, and this time, it work, i see my filters data. So my question is, is there a settings, decorator, flag or whatever that can force httprequest to parse content data h when content-length is absent for GET request ? Thanks -
How to paginate different objects of the same endpoint in Django Rest Framework?
Lest supose that I have a model named Collection. I can create a collection, this collection have two important fields: share_with_company, share_list. class Collection(models.Model): name = models.CharField(max_length=200, blank=False, null=False) share_with_company = models.BooleanField(default=False) share_list = ArrayField(models.CharField(max_length=15), null=True, blank=True) owner = models.CharField(max_length=200, blank=False, null=False) currently I have an endpoint: /collections and this endpoint need to return something like it: { shared_with_company:{collections: ..., count: 5} shared_list:{collections: ..., count: 12} my_collections:{collections: ..., count: 20} //dont shared with anyone, created by the current user } but, in the frontend the user want to paginate just my_collections or just shared_list or shared_with_company. I like performance, so should I create a specifics endpoints to each type of collections? But, everytime the user load the collections page will show 12 (max per page) collections of each (my_collections, shared etc.), and then he will be able to paginate it. I don't know if this is the best way to do it, I think a lot of users send 3 requests everytime the page is loaded. Another approach: use an endpoint to load the initial page, and this enpoint will make one request to the first page and the paginations will be made with differents endpoints. I really don't know … -
Django displaying each object in a button
Good day, I have a page to test where tickets are created and where all created tickets (titles) are listed. Now you should be able to click on the title of a created ticket. The button then redirects to an extra page where all the information of the specific ticket is. I've always had trouble displaying user specific stuff, so what needs to be done so that the href="" of each link redirects in HTML to the specific ticket? I did the following \\forms.py {% for i in request.user.addtitle_set.all %} <div> {% if i.user == request.user %} {{ i.title }} {% endif %} <form action="{% url SOMETHING_HERE i.id}" style="display: inline"> <button type="submit">Delete</button> </form> </div> <br /> {% endfor %} \\urls.py path('dashboard/user/ticket', ticket_view), path('dashboard/user/ticket/<int:id>/', ticket_system_view, name="view_ticket"), \\ models.py class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() creator_adress = models.GenericIPAddressField(null=True) start_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.title) \\views.py @login_required def ticket_view(request, id, *args, **kwargs): try: obj = Ticket.objects.get(id=id) except Ticket.DoesNotExist: return redirect('/') if request.method == 'POST': form = TicketForm(request.POST, instance=Ticket(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard/user/ticket') else: form = TicketForm() return render(request, 'ticket.html', {'form': form}) def ticket_system_view(request, id, *args, … -
ModuleNotFoundError: No module named 'app.project'
Mb I am idiot but I wanna know what I do wrong enter image description here enter image description here enter image description herestack.imgur.com/qtMOg.png -
Show list of another model in detail view
I want to show another model inside the detail view as a list. I have tried using "get_context_data" inside the DetailView but it does not show up inside the template. The model that I want to show is called "Questions". This is my code right now class ArticleDetailView(LoginRequiredMixin, DetailView): model = Article def get_context_data(self, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) context['questions'] = Questions.objects.filter(author=self.request.user) return context In my template I call for {{questions}} but nothing shows up. -
TypeError: bad argument type for built-in operation. I can't see the error
I have an error here which I can't figure out. This is for export a PDF Traceback (most recent call last): File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, *callback_kwargs) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\purchase\views.py", line 290, in view_sales_order_pdf textob.textLine(line) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\reportlab\pdfgen\textobject.py", line 445, in textLine self._code.append('%s T' % self._formatText(text)) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\reportlab\pdfgen\textobject.py", line 412, in _formatText for f, t in pdfmetrics.unicode2T1(text,[font]+font.substitutionFonts): Exception Type: TypeError at /view_sales_order_pdf/ Exception Value: bad argument type for built-in operation def view_sales_order_pdf(request): buf = io.BytesIO() c = canvas.Canvas(buf, pagesize=A4, bottomup=0) textob = c.beginText() textob.setTextOrigin(mm, mm) textob.setFont("Helvetica", 14) sales_orders = SalesOrder.objects.all() lines = [] for sales_order in sales_orders: lines.append(sales_order.so_number) lines.append(sales_order.customer) for line in lines: textob.textLine(line) c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='sales_order.pdf') -
Django handling database table names differently in Ubuntu vs Windows
I've built a Django application locally and I'm now trying to deploy it (or at least test) on an AWS EC2 instance using Ubuntu 20.04 (t2.micro). When hosted locally, the application works fine. When hosted on AWS, I get a ProgrammingError (1146, "Table 'database_name.exampleAppName_modelname' doesn't exist"). What I've tried On the server, using MySQL in the command line I've done: USE database_name; SHOW tables; Which lists tables as expected as: +----------------------------------------------+ | Tables_in_database_name | +----------------------------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | django_session | | **exampleappname_modelname** | The cause of the error seems to be fairly obvious in that Django is querying 'exampleAppName' but the database contains 'exampleappname' instead. However, when I run the same MySQL commands locally, I get exactly the same list of tables. And when I run the Django app locally there are no errors. I checked the names Django is automatically assigning the tables on the server and locally using the shell: ModelName._meta.db_table In both cases, this returns: 'exampleAppName_modelname', which leads to my question. What I'd like to know If the 'db_table' name auto-assigns the … -
how to connect bootstrap form to Django database to create a model instance
I am new to bootstrap and django both, so please don't mind my skills. I have made a custom bootstrap form for my todo app that will add item in the database which looks like this add task field here is the bootstrap code: <form method="post" class="form-control"> {% csrf_token %} {{ form.as_p }} <p class="lead"> Create your task: </p> <div class="form-row"> <div class="col-7"> <input type="text" class="form-control" placeholder="Enter your task here:" name="task"> </div> <div class="col-2"> <input type="time" class="form-control" placeholder="Enter your time here:" name="time"> </div> <div class="col-2"> <select class="custom-select mr-sm-2" id="inlineFormCustomSelect" name="status"> <option selected>Choose...</option> <option value="1">In Complete</option> <option value="2">Completed</option> </select> </div> <div class="col-1"> <button type="button" class="btn btn-outline-primary">Confirm</button> </div> <div class="row mt-3"></div> </div> </form> the model and the form are below: class Task(models.Model): choices = ( ('Completed', 'Completed'), ('In Complete', 'In Complete'), ) name = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) task = models.CharField(max_length=200, null=False, blank=False) time = models.TimeField(auto_now_add=False, blank=True) status = models.CharField(max_length=200, choices=choices, null=True, blank=False) def __str__(self): return self.task from django.forms import ModelForm from .models import * from django import forms class TaskForm(ModelForm): class Meta: model = Task fields = '__all__' and the view is: def create_task(request): form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = … -
Django The ChecklistItem could not be created because the data didn't validate
Creating a small function to add a new checklist item and i keep getting same error. Views.py @login_required def task_detail(request, slug): ''' Detailed view of all tasks on given project ''' context = {} checklist = get_object_or_404(Checklist, slug=slug) context.update({'checklist':checklist}) form = NotesForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n for is valid") author = Profile.objects.get(user=request.user) new_note = form.save(commit=False) new_note.user = author new_note.checklist = checklist new_note.save() return redirect('task_detail', slug=slug) context.update({ 'form': form, 'title': checklist, }) return render(request, 'projects/checklist.html', context) @login_required def new_checklist_item(request, slug): if request.method == 'POST': form = CheckListItemForm(request.POST) form.save() return redirect('task_detail', slug=slug) The checklist item is on the same page as the task_detail view, above urls.py urlpatterns = [ path('projects/', teams, name='teams'), path('projects/project/<slug>/', projects, name='projects'), path('projects/tasks/<slug>/', project_detail, name='project_detail'), path('projects/checklist/<slug>/', task_detail, name='task_detail'), # Create a new checklist item path('projects/checklist/new_checklist_item/<slug>/', new_checklist_item, name='new_checklist_item'), ] Then the form class CheckListItemForm(forms.ModelForm): class Meta: model = ChecklistItem fields = ['item'] Want to create a new checklist item on the page, What am i doing wrong on the view, am i missing something? the html <!-- Form for creating new checklist --> <form method="POST" action="{% url 'new_checklist_item' title.slug %}" class="modal fade" id="checklist-item-add-modal" tabindex="-1" aria-hidden="true"> {% csrf_token %} <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> … -
Align models with TabularInline django admin with models
How best can I align well my models which are in a reverse relationship with the help of TabularInline, I tried the following below but failed : class SubTopicInline(admin.TabularInline): model = models.SubTopic class CourseAdmin(admin.ModelAdmin): inlines = [SubTopicInline] admin.site.register(models.Course, CourseAdmin) This is the error thrown : ERRORS: <class 'courses.admin.SubTopicInline'>: (admin.E202) 'courses.SubTopic' has no ForeignKey to 'courses.Course'. Then below is my models : class Course(TimeStampedModel, models.Model): """ Course model responsible for all courses. :cvar uid: UID. :cvar title: Course title. :cvar description: Description of the course. :cvar course_cover: Image for the course. :cvar category: Course Category. :cvar user: Author of the course. :cvar review: Course review. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Meta: verbose_name_plural = "Courses" class SubTopic(TimeStampedModel, models.Model): """ Subtopic for the course. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) sub_topic_cover = models.ImageField( _('Sub topic Cover'), upload_to='courses_images', null=True, max_length=900) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) course = models.ManyToManyField(Course, related_name='sub_topic', blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Sub topic" class Lesson(TimeStampedModel, models.Model): """ Lesson for the sub topic. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, … -
Pagination in filtered queryset using Django Listview
I´m having a problem when using pagination in generic ListView, when trying to filter queryset. The filter works fine, but the thing is when trying to access a page that isn´t the first,an error appears: Invalid page (2): That page contains no results What if I remove all the pagination? What would you recommend? The goal of the template is to show date filtered sales in a list and also a client filter This is my code: class ListSales(LoginRequiredMixin, ListView): template_name = "sales/list.html" context_object_name = 'sales' login_url = reverse_lazy('users_app:user-login') paginate_by = 5 def get_queryset(self): client = self.request.GET.get("clientselect", "") date1 = self.request.GET.get("date1", '') date2 = self.request.GET.get("date2", '') if date1 == '': date1 = datetime.date.today() if date2 == '': date2 = datetime.date.today() queryset = Sale.objects.get_sales_list(date1, date2, client) return queryset And this my template: {% extends "panel.html" %} {% load static %} {% block panel-content %} <div class="grid-x medium-10"> <h3 class="cell medium-12" style="text-align: center;">Ventas</h3> <div class="cell medium-12">&nbsp </div> <form class="cell medium-10" method="GET">{% csrf_token %} <div class="input-group grid-x medium-12"> <div class="input-group cell medium-3 grid-x"> <label class="cell medium-12">Desde:</label> <span class="input-group-label"><i class="fi-calendar"></i></span> <input type="date" id="date1" name="date1" class="input-group-field" type="date"> </div> &nbsp&nbsp&nbsp <div class="input-group cell medium-3 grid-x"> <label class="cell medium-12">Hasta:</label> <span class="input-group-label"><i class="fi-calendar"></i></span> <input type="date" id="date2" name="date2" class="input-group-field" … -
Include search/filtering in my choicefield django
I have a CrispyForm where I have a ChoiceField called "act_cuenta" with choices that I load from a query. I want that in this field the user has the option to type and search for one of the options within the list. form.py class MayoresForm(Form): act_cuenta = () act_fechaini = DateField( widget=DatePickerInput( format=Form_CSS.fields_date_format, options=Form_CSS.fields_date_opts, attrs={'value': Form_CSS.fields_current_date} ), label="Fecha desde: ", required=True, ) act_fechafin = DateField( widget=DatePickerInput( format=Form_CSS.fields_date_format, options=Form_CSS.fields_date_opts, attrs={'value': Form_CSS.fields_current_date} ), label="Fecha hasta: ", required=True, ) def __init__(self, *args, **kwargs): self.AIGN_OPCIONES = kwargs.pop("AIGN_OPCIONES") self.PERMISOS = [] # para recuperar los permisos de la tabla __json_values = json.loads(json.dumps(self.AIGN_OPCIONES)) self.PERMISOS = recuperarPermisos(__json_values, 'con.transaccioncab') self.AIGN_PER_ID = kwargs.pop("AIGN_PER_ID") super(MayoresForm, self).__init__(*args, **kwargs) self.fields['act_cuenta'] = ChoiceField(label='Cuenta: ', choices=self.get_choices(), required=True) for form in self.visible_fields(): form.field.widget.attrs['autocomplete'] = Form_CSS.fields_autocomplete form.field.widget.attrs['class'] = Form_CSS.fields_attr_class self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.form_id = Form_CSS.getFormID(self) self.helper.attrs = Form_CSS.form_attrs self.helper.form_tag = True self.helper.label_class = 'col-sm-3 text-right form-control-sm' self.helper.field_class = 'col-sm-6' self.helper.layout = Layout( Div( DivHeaderWithButtons(instance_pk=None, remove_create=False, remove_delete=True, remove_print=True, remove_cancel=False, permisos=self.PERMISOS, save_name=' Consultar'), Div( Div( Div( Div( Div( HTML("<h3 class='card-title'>Buscar por:</h3>"), css_class='card-header' ), Div( Div( 'act_cuenta', css_class='card-body' ), Div( 'act_fechaini', 'act_fechafin', css_class='card-body' ), css_class="row" ), css_class='card card-secondary' ), css_class='col-sm', ), css_class='row', ), css_class='card-body' ), css_class='card' ), ) def get_choices(self): all_tipoaux = Con_Cuenta.objects.filter(cue_grupo='M', cue_estado=1, per_id=self.AIGN_PER_ID).order_by( 'cue_codigov').values() … -
Django to register multiple URL Nested and default
This is my URLs of the app router = routers.DefaultRouter() router.register(r'school', SchoolView, 'school-view') router.register(r'student', StudentView, 'student=view') school_router = routers.NestedDefaultRouter(router, r'school', lookup='school') school_router.register(r'students', StudentSchoolView, basename='student-school') urlpatterns = router.urls And am registering my URLs in the project URLs from django.contrib import admin from django.urls import path, include from student_school.urls import urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include(urlpatterns)) ] I want to have both the routes in my app URL, right now am only getting the URLs from the router(Default) but I also want to get the routes of the Nested Routes -
Django recursive models with through
I'm trying to set up a model such that the parts of the model can have parent or child relations to each other. It was working using the automatically generated 'relationship' table, but I needed to add an additional column for quantity. I thought I had hit gold when I found this in the documentation, but I can't seem to make it work. Here's my code: class Part(models.Model): name = models.CharField(max_length=100) parent = models.ManyToManyField( 'self', symmetrical=False, through='Relationship', through_fields = ('parent', 'child'), blank=True) class Relationship(models.Model): qty = models.IntegerField(default=1) parent = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='+', null=True) child = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='+', null=True) When I go to add a part, I can't add a parent to it. -
How to pass extra arguments to startapp command in bash?
I want to pass values to template_context and the docs says: Any option passed to the startapp command (among the command’s supported options) What I understand is, that any extra argument that I pass, it will be set to the context dictionary. But I'm receiving the same error (django-admin startapp: error: unrecognized arguments: --options=ok) django-admin startapp name_app --template="./templates" --options="ok" I also tried with - and without it django-admin startapp name_app --template="./templates" -a_value="ok" and django-admin startapp name_app --template="./templates" some_value="ok" How am I supposed to add the extra arguments? I know must be something easy, but I'm stuck for too much time now, and I couldn't find an example that uses it. -
Users instead id , Django(wagtail) , Vue
I want to make a class that returns usename of all users who liked the post. Users will be sent to Vue. currently the code returns in Vue consol log - 0: {likex: 'ideas.IdeaPage.None'} models.py class IdeaPage(Page): intro = models.CharField(max_length=250) body = RichTextField() tags = models.CharField(max_length=100, null=True, blank=True) likex = models.ManyToManyField(User, related_name="likex", blank=True) serializer.py class LikeSerializer(serializers.ModelSerializer): likex = serializers.CharField() class Meta: model = IdeaPage fields = ["likex"] views.py @authentication_classes([authentication.TokenAuthentication]) @permission_classes([permissions.IsAuthenticated]) class Like(APIView): def get(self, request, id, format=None): ideasl = IdeaPage.objects.get(id=id) likepost = IdeaPage.objects.get(id=id) likepostZ = likepost.likex.all() if request.user in likepost.likex.get_queryset(): likepost.likex.remove(request.user) else: likepost.likex.add(request.user) serializer = LikeSerializer(likepostZ, many=True) return Response(serializer.data) why code return likex: 'ideas.IdeaPage.None'? -
Celery delay task gets called twice but triggers only once
I am trying to run a celery task with multiple files. Simply put in a for loop I am calling the delay method on the task and I know that it gets called because I can see the logs before being called. However, the action inside the task itself gets executed only once. in my code I have something like this: def operation(*args, **kwargs): for arg in *args: time.sleep(2) # 2s interval celery_task.delay(kwargs) And the task actually look like this @shared_task(bind=True) def celery_task(**kwargs): do_something() # async So my question is: is there some kind of check that I can't see that prevents multiple tasks to be sent, or does it have something to do with different threads? Consider that I am not sending all the tasks at once, I am using an interval of 2 seconds before calling the task each iteration in the loop. -
How to make a django api view accessible to all users?
I'm creating a Django API view for a game by extending the rest_framework.views.APIView class. It's very likely that most users will not be authenticated. How can I enforce that? As far as I know there is no permissions.IsNotAuthenticated or similar. This is the part where I have trouble in my view, where I am trying to create a game round and game session object. I have tried working around this issue by creating a pseudo-user if the user isn't authenticated: if not isinstance(request.user, CustomUser): current_user = '1' else: current_user = request.user However, I keep getting this Value error message: Cannot assign "'1'": "Gamesession.user" must be a "CustomUser" instance. Below the code section from views.py current_score = 0 if not isinstance(request.user, CustomUser): current_user = '1' else: current_user = request.user gamesession = Gamesession.objects.create( id=controller.generate_random_id(Gamesession), user=current_user, gametype=gametype, created=datetime.now() ) gameround = Gameround.create({ 'id': controller.generate_random_id(Gameround), 'user': current_user, 'gamesession': gamesession, 'created': datetime.now(), 'score': current_score, }) gameround_serializer = GameroundSerializer(gameround) -
auth_token for unittest in Django
I've been trying to test my login system using the following code from django.test import TestCase, Client from rest_framework.test import force_authenticate class DeckTestCase(TestCase): @classmethod def setUp(cls): test_user1 = User.objects.create(first_name='tester',username='test1', password='123', email='testuser@something.com') def test_if_logged(self): factory = Client() user = User.objects.get(username='teste1') request = factory.post('/login', {'username': 'test1', 'password': '123'}, format='json') force_authenticate(request,user=user) print(request) But i keep getting this response, which is 401 (Unauthorized) <Response status_code=401, "application/json"> Can someone help me? I don't know how do I send an auth_token with test_if_logged -
How can I hide item entries in foreign key forms when they have 0 quantity in django forms?
I want to hide the item entries that are 0 or doesn't have any in stock, my current code for the item borrowing process is. Models.py class Activity(models.Model): Item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True) staff = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) project_site = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True) Quantity = models.PositiveIntegerField(null=True, default=1, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) date_created = models.DateTimeField(auto_now_add=True) is_draft = models.BooleanField(default=True) request_status = models.IntegerField(default=0, validators=[ MaxValueValidator(3) ]) return_status = models.IntegerField(default=0, validators=[ MaxValueValidator(3) ]) note = models.TextField(max_length=255, null=True) class Meta: verbose_name_plural = 'Item Request' def __str__(self): return f'{self.Item}' Forms.py class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ['Item', 'Quantity', 'project_site'] -
Django passing the post id from a button to the form
I got a button in html that is on the given post. This button opens up a form, that is hidden, until pressing the button. and the form itself is written further down on the page. The button <button class="btn btn-info" data-toggle="modal" data-target="#note-update-modal">Update</button> Then on the form for updating the post, i pass inn the post id, but it does not get the post id. the form, further down the html, that open up, when the update button is pressed <form method="POST" action="{% url 'update_notes' note.id title.slug %}" class="modal fade" id="note-update-modal" tabindex="-1" aria-hidden="true"> This form updated the post, but not the given post that the button presses, only takes the last posted post. I need a way to pass the id from the button, that is pressed to open the form, so that the form get the right id. Is there a way to do this? If somehow the question is not making sense please write, and yes the update function, the view, urls, everything work, it is just to get the right post. -
Django DigitalOcean Apps Deployment
I have a very small application that I am working on. I have everything up and running locally but can't get it deployed to DigitalOcean Apps. I have re-read all the tutorials and just can't get past this one spot. See the error below ModuleNotFoundError: No module named 'dj_database_url' So I have manually created the static file directories in the project, I ran the python manage.py collectstatic --noinput command locally and it did its job and put the files in the STATIC_ROOT directory. I also changed things out and the module name will change based on the order of the requirements.txt I really have no idea what I can do to fix this. Any help would be greatly appreciated. It feels like it is a really simple fix but I don't know what it is. -
I am getting this error Attribute Error and I have checked for the typos but found none
AttributeError at /api-auth/ Got AttributeError when attempting to get a value for field name on serializer UserDetailsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'name'. my model from django.db import models # Create your models here class UserDetails(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=100) virtualId = models.TextField(null=True, blank=True) photo = models.ImageField(upload_to='uploads/') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name serializers: from rest_framework.serializers import ModelSerializer from .models import UserDetails class UserDetailsSerializer(ModelSerializer): class Meta: model = UserDetails fields = '__all__' views : from rest_framework.response import Response from rest_framework.decorators import api_view from .models import UserDetails from .serializers import UserDetailsSerializer # Create your views here. @api_view(['GET']) def getAllUserdata(request): user = UserDetails.objects.all() serializer = UserDetailsSerializer(user) return Response(serializer.data)