Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to show relation(ManyToManyField) in html
I have traped show relation post by ManyToManyField python3 / django3.1 models.py class Post(models.Model): title = models.CharField(max_length=10) relation = models.ManyToManyField('self', blank=True) there is 3 posts post.title = [title1, title2, title3] title1 related [title1, title2, title3] index.html {% for p in post %} <p>{{ p.title }} </p> <p>{{ p.relation.all }}</p> {% endfor post %} the result is title1 <QuerySet [<Post: title1 >]> My question is how do I show all relation in {{ p.relation.all }} ? and I would like to remove this[ <QuerySet ] in html thank you for reading. -
heroku deployment for django react
I followed this precisely https://librenepal.com/article/django-and-create-react-app-together-on-heroku/ when I do git push heroku master everything succeeds. When I do heroku open it just takes me to application error page 2020-08-28T23:42:53.936006+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=6c4c0602-4239-4b39-a428-88796437ddfd fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:55.130985+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=loadedwhat.herokuapp.com request_id=61ab916b-8f79-4fff-bc0a-6583b96bd757 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:58.478573+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=6c70af08-0509-4c6d-a156-c1794b26b619 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:58.681158+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=loadedwhat.herokuapp.com request_id=45ca19c4-4463-4b70-8615-5bc29b1e71e6 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:59.789188+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=6ae32d53-7abd-44f8-b480-f3acc22f7b27 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:42:59.994456+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=loadedwhat.herokuapp.com request_id=d4e6b599-51f5-445b-a153-5b314e11d095 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:43:24.120340+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=7410e150-adfa-4be8-80d9-821415f55f50 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:43:24.430225+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=loadedwhat.herokuapp.com request_id=9ad8bc02-2811-459d-8c35-1a9cdce4248e fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:43:25.778014+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=loadedwhat.herokuapp.com request_id=678c2225-3fb8-42c5-8f5b-ee83792f7d94 fwd="73.15.209.31" dyno= connect= service= status=503 bytes= protocol=https 2020-08-28T23:43:25.983635+00:00 heroku[router]: … -
GraphQL query isn't refreshed with graphene-django
Here's my schema definition: class TemperatureRecordType(DjangoObjectType): unit = graphene.String() class Meta: model = TemperatureRecord fields = ("timestamp", "value") def resolve_unit(parent, info): return "Celcius" class Query(graphene.ObjectType): currentTemperature = DjangoListField(TemperatureRecordType) schema = graphene.Schema(query=Query) Query is : { currentTemperature{ timestamp value unit } } There's only one entry in TemperatureRecord, with value and timestamp changed by a management command every second running the refresh method in my model's class : class TemperatureRecord(models.Model): timestamp = models.DateTimeField(default=now) # Last time temperature value changed value = models.IntegerField(default=get_random_temperature_value) # Value to be changed every second, always in Celcius def refresh(self): # Updates entry's temperature value and timestamp self.value = get_random_temperature_value() self.timestamp = now() self.save() Here's the management command : class Command(BaseCommand): help = 'Refreshes temperature record every second, indefinitely' def handle(self, *args, **options): while True: time.sleep(1) try: TemperatureRecord.objects.get().refresh() except TemperatureRecord.DoesNotExist: TemperatureRecord.objects.create() Django shell works fine and shows data changes every second, but Graphene always returns the same stale data, and only refreshes if I change my schema and save the file. Is there some sort of caching? What am I doing wrong? -
django model optimization, fields applicable on two Models
I question myself on how to create my models well. I have Project Model which contains multiple Control (and each Control is applicable on multiple Project). But each Control got specific attributes for the Project I mean, a Project can have 10 Controls, and each control Applicable can be "Applicable" or "Not Applicable" Status can be "Not Planned", "Planned", "Done" So I made this : class Project(models.Model): name = models.CharField(max_length=100) code = models.PositiveSmallIntegerField("code", null=True, blank=True) description = models.TextField(default="") class Control(models.Model): control_description = models.TextField() and a third Model for the links between Project / Control / Others class ProjectControl(models.Model): APPLICABLE_CHOICES = ( ("A","Applicable"), ("NA","Not Applicable"), ) STATUS_CHOICES = ( ("D","Done"), ("NP", "Not Planned"), ("P", "Planned") ) project = models.ForeignKey('Project', verbose_name="Project", on_delete=models.CASCADE) control = models.ForeignKey('Control', verbose_name="Controle", on_delete=models.CASCADE) applicable = models.CharField(max_length=100, null=True, choices=APPLICABLE_CHOICES) status = models.CharField(max_length=100, choices=STATUS_CHOICES) Is there a better (or more conventional) way to do this ? I'm just facing an issue when using API, if I want all applicable controls of a project, I have to parse the whole ProjectControl Table, and I think, if the project goes big, performance issues. I tried this to resolve the issue by using M2M Field: class Project(models.Model): controls = models.ManyToManyField("Control", related_name="controls", default="", null=True, … -
Receiving form with two input at once and saving them separately with Django
I am trying to separately save two inputs that i named as item1 and item2 to different forms. But it doesn't work when i use request.POST['item1'] I tried to use get('item1') and getlist('item1') but none of them worked. How can i do it or can i do it actually? My HTML <form class="form-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="item1" > <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="item2" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> My Django file if request.method == 'POST': form1 = listForm(request.POST['item1']) form2 = listForm(request.POST['item2']) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() -
Getting a POST request to act like a GET request? djangorestframework-datatables
I don't want to add data to the database, like what djangorestframework-datatables is trying to do with the POST request. I need to use a POST request instead of a GET request because the URI for the GET request is too long (I had to change nginx and gunicorn limits on the production server, to unlimited length (max wasn't enough) which opens the site up to ddos attacks, which is obviously not ideal. Here is the code: # api/serializers class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report fields = "__all__" # api/views class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer # reports/models class Report(models.Model): contribution_expenditure_type = models.CharField(max_length=255, choices=CONTRIBUTION_EXPENDITURE_TYPES) filer_id = models.BigIntegerField() filer_namL = models.CharField(max_length=255) report_num = models.CharField(max_length=255) committee_type = models.CharField(max_length=255) rpt_date = models.CharField(max_length=255) from_date = models.CharField(max_length=255) thru_date = models.CharField(max_length=255) elect_date = models.CharField(max_length=255) rec_type = models.CharField(max_length=255) form_type = models.CharField(max_length=255, blank=True, null=True) tran_id = models.CharField(max_length=255, blank=True, null=True) entity_cd = models.CharField(max_length=255, blank=True, null=True) tran_namL = models.CharField(max_length=255) tran_namF = models.CharField(max_length=255, blank=True, null=True) tran_city = models.CharField(max_length=255, blank=True, null=True) tran_state = models.CharField(max_length=255, blank=True, null=True) tran_zip4 = models.CharField(max_length=255, blank=True, null=True) tran_emp = models.CharField(max_length=255, blank=True, null=True) tran_occ = models.CharField(max_length=255, blank=True, null=True) tran_self = models.CharField(max_length=255, blank=True, null=True) tran_type = models.CharField(max_length=255, blank=True, null=True) tran_date = models.CharField(max_length=255) tran_date1 = models.CharField(max_length=255, blank=True, null=True) … -
How to know when django is initializing for run or specific task/command?
I'm trying to use python sched module to start a scheduler when Django Server initializes, by running them from an AppConfig ready method. However, with this approach the scheduler is triggered whenever any django manage.py command is used. I would like to be able to handle only server initializations as runserver command, apache, nginx, etc. Are there any recommended approaches to handle this? -
UnboundLocalError at /create-full-article/
This is my views.py file. Im getting the following error. local variable 'formulario' referenced before assignment. I can't see the error in the code, i'm new at Django. from django.shortcuts import render, HttpResponse,redirect from miapp.models import Article from django.db.models import Q from miapp.forms import FormArticle def create_full_article(request): if request.method == 'POST': formualario = FormArticle(request.POST) if formulario.is_valid(): data_form = formulario.cleaned_data title = data_form['title'] content = data_form['content'] public = data_form['public'] articulo = Article( title = title, content = content, public = public ) articulo.save() return HttpResponse(articulo.title + ' ' + articulo.content + ' ' + str(articulo.public)) else: formulario = FormArticle() return render(request, 'create_full_article.html',{'form': formulario}) Im receiving data through POST method and validated the case of data coming through other methods but still getting this error. -
Custom Django Forms (crispy)
I have a registration form, I'm using crispy. I want to make the input fields look better so I wanted to add a class to each of them but the site only renders the first input field with the class. (This is my first django project so I'm pretty new to this) Here's my forms.py file: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.TextInput(attrs={'class': 'form-control input'}), 'email': forms.EmailInput(attrs={'class': 'form-control input'}), 'password1': forms.PasswordInput(attrs={'class': 'form-control input'}), 'password2': forms.PasswordInput(attrs={'class': 'form-control input'}), } Here's the template: <div class="sign-up"> <form class="form" method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4, sign-up__header">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign up</button> </div> </form> </div> -
Is there a cleaner way to save object to db than to declare props one by one like this:
How does this code look like to you? In html I have fields with name properties and I refer those names here. I just made this up myself havent seen similar examples. def addsupplier(request): a = request.POST['companyname'] b = request.POST['contactname'] c = request.POST['address'] d = request.POST['phone'] e = request.POST['email'] f = request.POST['country'] Supplier(companyname = a, contactname = b, address = c, phone = d, email = e, country = f).save() return redirect(request.META['HTTP_REFERER']) -
A more efficient Django (SQL) query
Working on a Django project, I have a database of users and artworks, the latter of which can be liked. I would like to query, to get how many likes on all their pictures a singular user has together. I am able to write that over two for loops in views.py, but that is slow. I've also written it as a separate (terrible) SQL query, but I'm not certain how to then use it properly, since it's not a query-set anymore (I guess I'd have to query in a way where I get all the required data?). The end idea is to simply have a table consisting of users, their emails, the number of likes their pictures have received, and the number of images posted. Here are the relevant models (I'm using the default Django auth_user table for users) and the SQL query. class Arts(models.Model): user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=False) title = models.CharField(max_length=100) description = models.TextField(unique=False, null=False, blank=True) timestamp = models.DateTimeField(default=timezone.now) url = models.URLField() likes = models.IntegerField(default=0) Artwork liked by user: class Like(models.Model): artwork = models.ForeignKey(Arts, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) my views.py for loop: def all_users(request): ... liked = defaultdict() for user in users_all: liked[user.id] = 0 for artwork … -
Django raising SynchronousOnlyOperation exception from Django Channels Async websocket consumer
Currently, I have an asynchronous consumer like this: class AsyncDashConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, code): await self.close() async def receive(self, text_data=None, bytes_data=None, **kwargs): print('>>>>>>Data received from client:', text_data) # get data # sendData.send(self.channel_name) sync_to_async(sendData.send(self.channel_name)) print('>>>>>>>First Worker Start') sync_to_async(sendData2.send(self.channel_name)) print('>>>>>>>Workers started') async def Dash_tester(self, event): await self.send(text_data=event['text']) async def Dash_tester2(self, event): await self.send(text_data=event['text']) The sendData functions inside async def receive are dramatiq (celery alternative) tasks: @dramatiq.actor def sendData(channelName): channel_layer = get_channel_layer() for i in range(20): async_to_sync(channel_layer.send)(channelName, {'type': 'Dash.tester', 'text': f'FirstFunction{i}'}) @dramatiq.actor def sendData2(channelName): channel_layer = get_channel_layer() for i in range(20): async_to_sync(channel_layer.send)(channelName, {'type': 'Dash.tester2', 'text': f'SecondFunction: {i}'}) My issue is with the sync_to_async(sendData.send(self.channel_name)) portion. When I try to use all this the client browser successfully gets the text string sent from the dramatiq task but this error arises: >>>>>>Data received from client: WEBSOCKET OPEN Unexpected failure in after_enqueue. Traceback (most recent call last): File "C:\Users\Timothee Legros\PycharmProjects\QuadkoRepository\Venv\lib\site-packages\dramatiq\broker.py", line 98, in emit_after getattr(middleware, "after_" + signal)(self, *args, **kwargs) File "C:\Users\Timothee Legros\PycharmProjects\QuadkoRepository\Venv\lib\site-packages\django_dramatiq\middleware.py", line 21, in after_enqueue Task.tasks.create_or_update_from_message( File "C:\Users\Timothee Legros\PycharmProjects\QuadkoRepository\Venv\lib\site-packages\django_dramatiq\models.py", line 16, in create_or_update_from_message task, _ = self.using(DATABASE_LABEL).update_or_create( File "C:\Users\Timothee Legros\PycharmProjects\QuadkoRepository\Venv\lib\site-packages\django\db\models\query.py", line 587, in update_or_create with transaction.atomic(using=self.db): File "C:\Users\Timothee Legros\PycharmProjects\QuadkoRepository\Venv\lib\site-packages\django\db\transaction.py", line 175, in __enter__ if not connection.get_autocommit(): File "C:\Users\Timothee Legros\PycharmProjects\QuadkoRepository\Venv\lib\site-packages\django\db\backends\base\base.py", line … -
How to be live with django using postgress website?
I have created a website using djnago ,html,css and js .I have used Postgresql for local database.I want to implement it live using a hosting service.So what's the way to make all this live?I do have bought a domain.I want to host it.Can someone help me regarding this? -
django how to format date to DD/MM/YYYY
django how to format date to DD/MM/YYYY in this case : class Invoice(models.Model): date = models.DateField(default=timezone.now) class InvoiceForm(ModelForm): class Meta: model = Invoice fields = "__all__" -
how to set a place holder to widgets in a sign up view (forms.PasswordInput()) Django
I am trying to give my {{form.password1}} a placeholder. #The concept is like this: <input type="password" placeholder="password"> I tried to do in django using django and this is my sign up form: from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django import forms class CreateUser(UserCreationForm): class Meta: model = User fields = ['username','email','password1', 'password2'] widgets = { 'username' : forms.TextInput(attrs={'class':'username', 'placeholder':'Username'}), 'email' : forms.TextInput(attrs={'placeholder':'Email'}), 'password1' : forms.PasswordInput(attrs = {'placeholder': 'Password'}), 'password2' : forms.PasswordInput(attrs={'placeholder':'Confirm Your Password'}), } But It doesn't show the password1 and password2 placeholders This is my register.html: <form method="POST"> {% csrf_token %} <div>{{form.username}}</div> <div>{{form.email}}</div> <div>{{form.password1}}</div> <div>{{form.password2}}</div> <input type="submit" placeholder="Register"> </form> -
How to loop through tags on sidebar with unique, and get all tags from the blog, not only from current page
So i have this blog and i want to display all the tags of the blog on the sidebar, i manage to loop through them But if i have 2 posts with the same tag, this (tag) get repeated in the sidebar loop and i don't know how to fix this. I think that maybe if i make the tags Unique that can help, but not really because i will not be able to make posts with the same tag, but i need to do something like Unique on the sidebar. Another issue is that i realize that i'm not getting all the tags from the blog in the sidebar, its getting all the tags of the current page only (because i have pagination). Deployed blog: https://azhierblog.herokuapp.com/ models.py: from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from taggit.managers import TaggableManager from ckeditor.fields import RichTextField class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = RichTextField(blank=True, null=True) # body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status … -
run external project in pycharm
hi i download this source over net: https://abrito.ir/uloader/UFD/toplearn_eshop.rar mirror link: https://gofile.io/d/Tas89h when i open folder by pycharm and config pycharm interpreter i got this error: https://paste.ubuntu.com/p/wMDq9vwJr3/ File "C:\Users\arashsoft\PycharmProjects\toplearn_eshop\lib\site-packages\django\utils\autoreload.py", line 274, in watched_files yield from iter_all_python_module_files() File "C:\Users\arashsoft\PycharmProjects\toplearn_eshop\lib\site-packages\django\utils\autoreload.py", line 105, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Users\arashsoft\PycharmProjects\toplearn_eshop\lib\site-packages\django\utils\autoreload.py", line 141, in iter_modules_and_files resolved_path = path.resolve(strict=True).absolute() File "C:\Users\arashsoft\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 1177, in resolve s = self._flavour.resolve(self, strict=strict) File "C:\Users\arashsoft\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 200, in resolve return self._ext_to_normal(_getfinalpathname(s)) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' -
Django-import-export - How to pass user information to ForeignKeyWidget?
I need to somehow pass the user information to ForeignKeyWidget class from resource class, where I create ForeignKey object: class CompanyWidget(ForeignKeyWidget): def clean(self, value, row=None, *args, **kwargs): print(self.user, file=sys.stderr) if not value: return None else: obj, _ = Company.objects.get_or_create( name=value, created_by='I NEED USER INFORMATION HERE SOMEHOW', ) return obj What is the best way to do this? I've tried to solve this on my own and got pretty close, but could not fit the last piece of the puzzle. You override __init__ class in resource and get user information there. Then, I could not figure out how to pass this self.user information into the class variable company. Here is the code: class ContactResource(resources.ModelResource): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(ContactResource, self).__init__(*args, **kwargs) company = fields.Field( column_name='company', attribute='company', widget=CompanyWidget(model=Company, field='name', user='I NEED TO PASS USER HERE FROM __INIT__')) created_by = fields.Field( column_name='created_by', attribute='created_by', widget=ForeignKeyWidget(User, 'email')) class Meta: model = Contact skip_unchanged = True report_skipped = True exclude =('is_active') export_order = ('first_name','last_name','email','phone','address','description','company','created_on','website','job_title','birthday') def after_import_instance(self, instance, new, **kwargs): instance.created_by = kwargs['user'] If I somehow manage to pass user information in **kwargs of company variable, then I can use it downstream by overriding ForeignKeyWidget's __init__ class: class CompanyWidget(ForeignKeyWidget): def __init__(self, model, field='pk', … -
My pytest throws this error django.db.utils.InterfaceError: connection already closed
My pytest throws this error: django.db.utils.InterfaceError: connection already closed My test case does the following: def test_autosignupanonymoususer_with_good_key_success(db, client): response = client.post(path='http://127.0.0.1:8080/api/accounts/autosignupanonymoususer', data={"device_serial": "device1", "device_brand": "Apple", "device_version": "1.0", "device_country": "US", "token_key": "123456testkey"}) assert response The API view looks like this class AutoSignupAnonymousUserView(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): data = request.data serializer = AutoSignupAnonymousUserRequestSerializer(data=data) serializer.is_valid(raise_exception=True) # The error originates from is_valid_key() definition if is_valid_key(serializer.validated_data.get("token_key"), request=request): . . . The definition of is_valid_key looks like def is_valid_key(key, request): host = request.get_host() if host == 'testserver': #---> This condition throws the error url = reverse('validate-key', request=request) client = RequestsClient() #---> I this this lines causes the error res = client.get(url=url, headers={"Authorization": "Token " + key}) #---> I this this lines causes the error else: #---> This condition works successfully res = requests.get(reverse('validate-key', request=request), headers={"Authorization": "Token " + key}) if res.status_code == 200: return True return False validate-key URL looks like path('api/validatekey/', views.ValidateKey.as_view(), name='validate-key') ValidateKey definition looks like this: class ValidateKey(views.APIView): # My default permission classes is 'rest_framework.permissions.IsAuthenticated' def get(self, request): return Response({"success": True}) When I run pytest, I get this error django.db.utils.InterfaceError: connection already closed The stacktrace is self = <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f8d7ba50fa0>, name = None @async_unsafe def create_cursor(self, name=None): if name: … -
Website looks different on 2 different live servers
I have a website which I made using npm's liveserver. Now I wanted to make a backend for it so now I use Django. (with its basic server). The website looks kind of the same, but it seems like it added a huge margin to the sides. I tried removing the margin but that didn't help. Will this be a problem when I deploy the site on a real webhost? -
FieldError at /add-to-cart/test-product1
Hello guys i need help here please, while trying my dd to cart button i received this message. FieldError at /add-to-cart/test-product1/ Cannot resolve keyword 'ordered' into field. Choices are: id, item, item_id, order, quantity my views.py for the add to cart function. def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) return redirect("store:product", slug=slug) my models.py class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username -
Django crispy forms: Controls do not fill entire layout horizontally
I'm learning how to use Crispy Forms, following Vitor Freitas' tutorial. However, when pasting his exact code in a form and in a template, the text boxes do not fill horizontally the space as intended. The code (copied from Vitor's site): from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column STATES = ( ('', 'Choose...'), ('MG', 'Minas Gerais'), ('SP', 'Sao Paulo'), ('RJ', 'Rio de Janeiro') ) class AddressForm(forms.Form): email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput()) address_1 = forms.CharField( label='Address', widget=forms.TextInput(attrs={'placeholder': '1234 Main St'}) ) address_2 = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Apartment, studio, or floor'}) ) city = forms.CharField() state = forms.ChoiceField(choices=STATES) zip_code = forms.CharField(label='Zip') check_me_out = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('email', css_class='form-group col-md-6 mb-0'), Column('password', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), 'address_1', 'address_2', Row( Column('city', css_class='form-group col-md-6 mb-0'), Column('state', css_class='form-group col-md-4 mb-0'), Column('zip_code', css_class='form-group col-md-2 mb-0'), css_class='form-row' ), 'check_me_out', Submit('submit', 'Sign in') ) Intended layout: Actual result in my experiment: The HTML code: base.html <!DOCTYPE html> {% load static %} <html lang='sp'> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <title> {% block title %} Page title {% endblock title %} </title> … -
Display subprocess output from django to browser
I have simple django application on which user upload some file and django will use that file and run external executable app using subprocess. It runs about 50 seconds and I want to continuously display log from this subprocess. I can read whole output and display it but I want to see the program as it runs. Could you please suggest some approach how to do that? -
django.contrib.auth.urls noReverseMatch
I am using path('accounts/', include('django.contrib.auth.urls')), in urls.py and when i go to /accounts/login I get this error: NoReverseMatch at /accounts/login/ Reverse for 'password_reset' not found. 'password_reset' is not a valid view function or pattern name. I have the login template, so what's wrong? -
use Django with two Vuejs components project
so i have a project that i created with vuejs and django, for authentication i did it with session authentification. so when it connects it launches vue js project but i wanted to know can i do it when it won't be authentify like do i create a new vuejs project or i can use the old one. or tell me if you have a other proposition . ps: i know that there are Jwt Authentification] #python url to lunch vuejs re_path(r"^(?!media/).*$", IndexTemplateView.as_view(), name="entry-point"), the view : class IndexTemplateView(LoginRequiredMixin, TemplateView): def get_template_names(self): if not settings.DEBUG: template_name = "index.html" else: template_name = "index-dev.html" return template_name