Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django ModelForm datetime field don't accept html form input datetime-local
i want to create django model object from django ModelForm with post method from client but html form input datetime-local don't match format with field in django model. models.py class Event(models.Model): start_date = models.DateTimeField(blank=False) end_date = models.DateTimeField(blank=False) forms.py class CreateEvent(forms.ModelForm): class Meta: models = Event add_event.html <input type="datetime-local" class="form-control" id="..." name="..."> -
Does the stripe need to create PaymentIntent for real payment?
I am new to stripe, and I code for the stripe payment function in the django project,I already test that's fine for the test payment, is it enough just use the charge API of stripe? the js is simply copy from the stripe API. views.py: def payment_process(request): stripe.api_key = settings.STRIPE_SECRET_KEY token = request.POST.get('stripeToken') order = Order.objects.get(user=request.user, ordered=False) amount = int(order.get_total() * 100) if request.method == 'POST': try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token, ) print('get the charge') payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = request.user payment.amount = order.get_total() payment.save() print('payment saved') order.ordered = True order.payment = payment order.save() print('order saved') messages.success(request, "Payment Succeed") return redirect('/') except ObjectDoesNotExist: messages.error(request, 'Payment Failed') return redirect('/') else: return render(request, 'payment.html') Html is copy from the simple example: <div class="new-card-form"> <form action="." method="post" class="stripe-form" id="payment-form"> {% csrf_token %} <div class="stripe-form-row" id="creditCard"> <label for="card-element" id="stripeBtnLabel"> Credit or debit card </label> <div id="card-element" class="StripeElement StripeElement--empty"> <div class="__PrivateStripeElement" style="margin: 0px !important; padding: 0px !important; border: none !important; display: block !important; background: transparent !important; position: relative !important; opacity: 1 !important;"> <iframe frameborder="0" allowtransparency="true" scrolling="no" name="__privateStripeFrame5" allowpaymentrequest="true" src="https://js.stripe.com/v3/elements-inner-card-19066928f2ed1ba3ffada645e45f5b50.html#style[base][color]=%2332325d&amp;style[base][fontFamily]=%22Helvetica+Neue%22%2C+Helvetica%2C+sans-serif&amp;style[base][fontSmoothing]=antialiased&amp;style[base][fontSize]=16px&amp;style[base][::placeholder][color]=%23aab7c4&amp;style[invalid][color]=%23fa755a&amp;style[invalid][iconColor]=%23fa755a&amp;componentName=card&amp;wait=false&amp;rtl=false&amp;keyMode=test&amp;origin=https%3A%2F%2Fstripe.com&amp;referrer=https%3A%2F%2Fstripe.com%2Fdocs%2Fstripe-js&amp;controllerId=__privateStripeController1" title="Secure payment input frame" style="border: none !important; margin: 0px !important; padding: 0px !important; width: 1px !important; min-width: 100% !important; overflow: hidden … -
Override perform_create in Django Restframework
I have a Django Restframework project where User can write restaurants reviews. Here are my models: class RestaurantId(models.Model): maps_id = models.CharField(max_length=140, unique=True) adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class StarterPics(models.Model): restaurant_review_id = models.OneToOneField(RestaurantReview, on_delete=models.CASCADE) pics_author = models.ForeignKey(User, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) name_1 = models.CharField(max_length=40) picture_1 = models.ImageField() My serializers: class RestaurantIdSerializer(serializers.ModelSerializer): class Meta: model = RestaurantId field = fields = '__all__' class RestaurantReviewSerializer(serializers.ModelSerializer): class Meta: model = RestaurantReview field = fields = '__all__' def validate_restaurant_review_id(self, value): if value.review_author != self.context['request'].user: raise serializers.ValidationError("User has not reviewed the restaurant") return value class StarterPicsSerializer(serializers.ModelSerializer): class Meta: model = StarterPics fields = '__all__' def validate_restaurant_review_id(self, value): if value.review_author != self.context['request'].user: raise serializers.ValidationError("User has not reviewed the restaurant") return value And my views: class RestaurantIdViewset(viewsets.ModelViewSet): queryset = models.RestaurantId.objects.all() serializer_class = serializers.RestaurantIdSerializer class RestaurantReviewViewset(viewsets.ModelViewSet): queryset = models.RestaurantReview.objects.all() serializer_class = serializers.RestaurantReviewSerializer permission_classes = [IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly] def perform_create(self, serializer): serializer.save(review_author=self.request.user) class StarterPicsViewset(viewsets.ModelViewSet): queryset = models.StarterPics.objects.all() serializer_class = serializers.StarterPicsSerializer permission_classes = [IsAuthenticatedOrReadOnly, IsOwnReviewOrReadOnly] def perform_create(self, serializer): serializer.save(pics_author=self.request.user) What I want is that review_author is not able to POST a picture in StarterPics with another restaurant_id that the one matching the RestaurantReview_id. I tried … -
How do I convert a blob file passed through rest to imagefield django?
My web application receives an image via the api in blob format(it is cropped there by the user) and I need to accept it, convert it to imagefield and save it to the user. I wrote this code in the serializer, nothing changes and the value of variables I also do not see(whether validated_data is exactly in this format as I think). serializers.py: class ProfileSerializer(serializers.ModelSerializer): # image = serializers.ImageField(use_url=True) class Meta: model = User fields = ["first_name", "last_name", "email", "image"] def create(self, validated_data): user = User.objects.get(email=validated_data['email']) user.update(**validated_data) with io.BytesIO(validated_data['image']) as stream: django_file = File(stream) user.image.save('{}_profile_image'.format(user.email), django_file) return user.save() views.py: class UserProfile(generics.RetrieveUpdateDestroyAPIView, generics.CreateAPIView): queryset = User.objects.all() serializer_class = ProfileSerializer permission_classes = (IsAuthenticated,) def get_object(self): queryset = self.filter_queryset(self.get_queryset()) obj = queryset.get(pk=self.request.user.id) # May raise a permission denied self.check_object_permissions(self.request, obj) return obj def create(self, request, *args, **kwargs): if not request.data: return response.Response({"result": "data can`t be a blanks"}, status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return response.Response(serializer.data, status=status.HTTP_201_CREATED) -
Django REST - JSON gets returned with backslashes (serilized mutpiple times?)
I have defined the following function in the backend for getting JSON responses def create(self, request, *args, **kwargs): import requests import json url = request.POST.get('url') r = requests.get(url) return Response(json.loads(r.content.decode('utf-8'))) It works perfectly when used outside of a django view (if i remove all the function arguments and pass in a url) This is the output when sending a sample request to the Twitter API { "url": "https://twitter.com/elonmusk/status/1285830270709403648", "author_name": "Elon Musk", "author_url": "https://twitter.com/elonmusk", "html": "<blockquote class=\"twitter-tweet\"><p lang=\"en\" dir=\"ltr\">You don’t have a soul, you are a soul</p>&mdash; Elon Musk (@elonmusk) <a href=\"https://twitter.com/elonmusk/status/1285830270709403648?ref_src=twsrc%5Etfw\">July 22, 2020</a></blockquote>\n<script async src=\"https://platform.twitter.com/widgets.js\" charset=\"utf-8\"></script>\n", "width": 550, "height": null, "type": "rich", "cache_age": "3153600000", "provider_name": "Twitter", "provider_url": "https://twitter.com", "version": "1.0" } No only do the strings get wrapped in double quotes \ \ but also arguments like \n , blockquote are kept in the response I know it has something to do with the response beeing serialized multiple times but I can't find exactly when this happens Slightly Modifying the response to return the raw data returns this return Response({ "json_serialized" : json.loads(r.content.decode('utf-8')), "raw_content" : r.content.decode('utf-8') }) Here is the output { "json_serialized": { "url": "https://twitter.com/elonmusk/status/1285830270709403648", "author_name": "Elon Musk", "author_url": "https://twitter.com/elonmusk", "html": "<blockquote class=\"twitter-tweet\"><p lang=\"en\" dir=\"ltr\">You don’t have a soul, … -
How to directly access Webcam snapshot in django form ImageField upload?
class Visitor(models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics/', null=True, blank= True, help_text = " Note:- Drag and drop downloaded image on [!Choose File!] or browse from folder !!") address = models.TextField(null=True) date = models.DateTimeField(auto_now_add=True, null=True) -
How do i use session authentication in a two-project Django application?
I have a separate front & backend on the same domain, both in Django, for a user portal-style app. The front end has no database access. in my backend, I've set up a custom auth backend, using Django's session authentication, which works fine for logging in. but when trying to access request.user of a subsequent call from the frontend, request.user is an AnonymousUser. I'm guessing this is because the front end doesn't know about the current user, as it' done in the backend, so it's not included in the request. How do i get session authentication to work, when there are two projects? Do i need some middleware to set request.user every time? Or store the session data as cookies instead of in the db? -
CheckboxSelectMultiple in crispy forms, custom data attribute
I want to override the CheckboxSelectMultiple so I can give data- attributes to the form using the logic below: class MySelect(forms.Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option = super(forms.Select, self).create_option(name, value, label, selected, index, subindex, attrs) if value: for k,attr in self.attrs.items(): # if it has a data attr in it if k[:4] == 'data': #instantiate a new object and add the data attr to the option current_object = self.choices.queryset.model.objects.get(pk=value) option['attrs'].update({ k: getattr(current_object, attr) }) return option This works just fine for non-crispy forms but since crispy never call this method, it won'w work this way. I want to override the CheckboxSelectMultiple create_option method. What is an elegant way to solve this issue without having to override the whole form field rendering process? I tried to use a custom html but it is so complicated (for my skills) to get a decent working CheckboxSelectMultiple with the checked attribute. -
Django SearchFilter, Cannot resolve keyword
I have model class Emails(models.Model): mail_theme = models.CharField(max_length=254, blank=True) in my view i have added from rest_framework import filters class EmailsView(generics.ListCreateAPIView): permission_classes = (permissions.AllowAny, ) serializer_class = EmailsSerializer filter_backends = (filters.SearchFilter, DjangoFilterBackend, ) filter_fields = ('is_paid', 'new_item', 'mail_from') search_fields = 'mail_from' def get_queryset(self, *args, **kwargs): return Emails.objects.all() but when i try to use mail_from field for search, i had an error: Cannot resolve keyword 'm' into field. Choices are: id, mail_from -
React JSX: setting variable leads to page not being loaded
I have a question regarding setting a specific variable based on another. I have stored the gender of the user in the database as U, M, F. U stands for Undefined, M for Male, F for Female etc. now I want to show the text Undefined instead of U and Male instead of M. export const AccountTile: React.FC = () => { const [isEditing, setIsEditing] = React.useState(false); const [setAccountUpdate, { data, error }] = useAccountUpdate(); const { data: user } = useUserDetails(); let userGender = user.gender; if(userGender === "U"){ userGender = "Undefined"; } React.useEffect(() => { if (data && !error) { setIsEditing(false); } }, [data, error]); return ( <S.TileWrapper> <Tile> <S.Wrapper> <S.Header>MY DATA</S.Header> <S.Content> <S.HeaderSmall> Personal details {!isEditing && ( <IconButton name="edit" size={22} onClick={() => setIsEditing(isEditing => !isEditing)} /> )} </S.HeaderSmall> {isEditing ? ( <AccountUpdateForm initialValues={{ birthday: (user && user.birthday) || "", firstName: (user && user.firstName) || "", gender: (user && user.gender) || "", lastName: (user && user.lastName) || "", }} handleSubmit={data => { setAccountUpdate({ input: data }); }} hide={() => { setIsEditing(false); }} /> ) : ( <S.ContentOneLine> <Attribute description="First Name" attributeValue={(user && user.firstName) || "-"} /> <Attribute description="Last Name" attributeValue={(user && user.lastName) || "-"} /> <Attribute description="Birthday" attributeValue={(user … -
See all chat rooms that user has in django-channels
I am making a website, this website has a chat app include, the chat app works perfect, but there is a thing I want to do but I dont know how to do it. So I have this chat view chat view, here is were there is the websocket and all that stuff, But in this view this view, is the place were I want the user to see all the chat rooms he is in, on the side of chats like the two example users that are in there. the problem is that I don´t know how to do it. can someone tell me how to do it? with a simple example, like a very simple chat, that the chats of the user appear in the home page?, thanks for the help. -
Django authentification: reset password -> connexion failed because re-direction to local url?
I've implemented the Django authentification app following this tuto : https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html until now I never had problem my project is currently in test in a remote server and now reset password failed is it cliend-side problem or server side problem? How can I resolve the problem? I think problem deal with the password_reset_email.html template where domain is defined but... password_reset_email.html Une demande de modification de mot de passe a été demandé par {{ email }}. Veuillez suivre ce lien : {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} settings.py """ Django settings for moderato project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+t82qxux+e78kx*zn!mwdr_vr#u%w@h0vdda-aosqh@^=y(1ul' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'widget_tweaks', 'bootstrap4', # 'randomization.apps.RandomizationConfig', # 'randomization_management.apps.RandomizationManagementConfig', … -
What is the difference between a JsonResponse and a HTTPResponse?
I am following a tutorial and the guy used these two lines of code. I am trying to understand the difference between a JsonResponse and a HttpResponse. Both the JsonResponse and the HttpResponse leads to the user getting a pop up message ($.alert({). When the output in both cases is an $.alert({, I am slightly confused why you need a JsonResponse in one instance and a HttpResponse in another. if request.is_ajax(): return JsonResponse({"message": "Thank you for your submission"}) if request.is_ajax(): return HttpResponse(errors, status=400, content_type='application/json') views.py if contact_form.is_valid(): print(contact_form.cleaned_data) if request.is_ajax(): return JsonResponse({"message": "Thank you for your submission"}) if contact_form.errors: print("there are errors") errors = contact_form.errors.as_json() if request.is_ajax(): return HttpResponse(errors, status=400, content_type='application/json') ecommerce.js displaySubmitting(contactFormSubmitBtn, "", true) $.ajax({ method: contactFormMethod, url: contactFormEndpoint, data: contactFormData, success: function(data){ contactForm[0].reset() $.alert({ title: "Success!", content: data.message, theme: "modern", }) setTimeout(function(){ displaySubmitting(contactFormSubmitBtn, contactFormSubmitBtnTxt, false) }, 500) }, error: function(error){ console.log(error.responseJSON) var jsonData = error.responseJSON var msg = "" $.each(jsonData, function(key, value){ // key, value array index / object msg += key + ": " + value[0].message + "<br/>" }) $.alert({ title: "Oops!", content: msg, theme: "modern", }) Here is the contact form Here is the contact form when you have entered the correct data Here is the … -
Django media files and user uploaded content in production
This question was evidently asked and answered many times. Unfortunately, most answers are either old (not applicable for Django 3), or not very explicit. I understand it is not recommended to serve media files and user uploaded content (such as photos or videos) with Django, and it is recommended to use a separate server. My question is, how exactly do I do that? Do I serve the files directly with apache / nginx in the same environment (is it safe and secure to do so?)? How do I point to it in a template (say, display a user avatar in a profile page)? Do I need a cloud storage or a different server entirely? How do I point Django to it then? I couldn't find any answers or documentation addressing this questions. What I found either refers to static files, or is presented as "development only") -
I set permission_required as "is_staff" and I got error 403 permission denied
I developped a webapp with Django and I want to protect a class view with permission. It should be only authorized for admin so I added this : permission_required = 'is_staff' But when I try to access to the view with my admin profiles (and I set their status as staff) I got this error : 403 Forbidden, permission denied. The fact is that if I try with super user profile it works. So I don't understand why 'is_staff' is recognized as 'is_superuser' Thank's for reading -
How can I cycle through dictionary on click in Django?
I'm building a simple flashcards web app. I've filtered my flashcards according to the deck and passed them to the deck template. I'm looking for a way to cycle through these cards on click. So when I click on a button, the next card in the deck will show. I suppose I could increment some value on click, and then use that show the card I'm looking, but I'm not sure how I would go about this in Django. Any ideas? View: class DeckDetailView(LoginRequiredMixin, DetailView): model = Deck def get_context_data(self, *args, **kwargs): deck = self.get_object() deck_title = deck.title context = super(DeckDetailView, self).get_context_data(*args, **kwargs) context['cards'] = Card.objects.filter(decks__title=deck_title) return context Models class Deck(models.Model): title = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Card(models.Model): question = models.CharField(max_length=100) answer = models.TextField() date = models.DateTimeField(default=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) decks = models.ManyToManyField(Deck) def __str__(self): return self.question Template {{ deck.title }} {% for card in cards reversed %} <div class="my-column col-xl-4 mt-2 "> <div class="card"> <div class="card-body"> <h5 class="card-title"> {{card.question}} </h5> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <a href="{% url 'mypage-study-deck' deck.id %}"> <button type="button" class="btn btn-success"> Study this Deck </button> </div> </div> </div> … -
ValueError : The QuerySet value for an exact lookup must be limited to one result using slicing
I'm getting this error when I shifted my code from Django 1.9 to django 2.2.9 version. It's perfectly working in django 1.9 but Can Anyone tell what has changed in 2.2.9 for this specific search. This is the Error I'm getting, I am stuck. I tried django doc. help! def search(request): locations = Location.objects.all()#.order_by('location_name') departments = Department.objects.all()#.order_by('department_name') if not request.GET.get('location', 'none') == 'none' and not request.GET.get('specialty', 'none') == 'none': location = request.GET.get('location',None) specialty = request.GET.get('specialty',None) location = Location.objects.filter(location_name=location) hospitals = Hospital.objects.filter(location=location) # doctors = DoctorProfile.objects.filter(user.first_name__contains=first_name) doctors = [] for hospital in hospitals: specialty = Department.objects.filter(department_name=specialty) doctors = DoctorProfile.objects.filter(hospital=hospital, specialization=specialty) return render(request, 'infrastructure/search.html', {'doctors': doctors, 'locations': locations, 'departments': departments}) return render(request, 'infrastructure/search.html', {'locations': locations, 'departments': departments}) -
Upgrade PostgreSQL from 9.6 to 11
I'm using the PostgreSQL v9.6 database for my Django (v1.11) application and I want to move to PostgreSQL v11. Are there any changes that need to be made before? Any risks for my Django application? Any pitfalls to avoid? I've checked the release notes of PostgreSQL but I just want to know if anyone has experienced issues after upgrading. -
Model 'courses.text' was already registered
I am Using Django Version 3 I have created a Django Project. Currently it contains only one app. that is courses. I am getting Error in the models.py file of the courses application. from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.utils import timezone from .fields import OrderField # Create your models here. class Subject(models.Model): title=models.CharField(max_length=200) slug=models.SlugField(max_length=200,unique=True) class Meta: ordering=['title'] def __str__(self): return self.title class Course(models.Model): title=models.CharField(max_length=200) owner=models.ForeignKey(User,related_name="courses_created",on_delete=models.CASCADE) subject=models.ForeignKey(Subject,related_name="courses",on_delete=models.CASCADE) slug=models.SlugField(max_length=200,unique=True) overview=models.TextField() created=models.DateTimeField(auto_now_add=True) class Meta: ordering=['-created'] def __str__(self): return self.title class Module(models.Model): course=models.ForeignKey(Course,related_name="modules",on_delete=models.CASCADE) title=models.CharField(max_length=200) descripion=models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) def __str__(self): return self.title class Content(models.Model): module=models.ForeignKey(Module,related_name="contents",on_delete=models.CASCADE) content_type=models.ForeignKey(ContentType,limit_choices_to={'model__in':('text', 'video', 'image', 'file')},on_delete=models.CASCADE) object_id=models.PositiveIntegerField() item=GenericForeignKey('content_type','object_id') class BaseContent(models.Model): title=models.CharField(max_length=100) created=models.DateTimeField(auto_now_add=True) class Meta: abstract=True class Text(BaseContent): body=models.TextField() class BaseContent(models.Model): title=models.CharField(max_length=100) created=models.DateTimeField(auto_now_add=True) class OrderedContent(BaseContent): class Meta: proxy=True ordering=['created'] def created_delta(self): return timezone.now-self.created class ItemBase(models.Model): owner=models.ForeignKey(User,related_name='%(class)s_related',on_delete=models.CASCADE) title=models.CharField(max_length=250) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: abstract=True def __str__(self): return self.title class Text(ItemBase): content=models.TextField() class File(ItemBase): file=models.FileField(upload_to='files') class Image(ItemBase): file=models.FileField(upload_to='images') class Video(ItemBase): url=models.URLField() Error Console Image Question: What did I do which resulted to that error? I am new to Django and Python. Thank you very much! -
Combining two models in one form?
I am creating an Invoice App. I would like to be able to add some item to an invoice. To achieve this, the app got two models: Invoice and InvoiceItem. I have combined the two models into one form. What I am trying to achieve now is to able able to add some item in the table of the invoiceform. At this moment, I can only add one item. I have added a button in the form to add a new item, but its getting confusing and I wonder if there is a different way to achieve this. The button doesnt work at this moment and the items in the table as well. Many thanks, models.py class Invoice(models.Model): TERMS = ( (0, '30 days'), (1, '45 days'), (2, '60 days'), ) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) currency = models.ForeignKey(Currency, on_delete=models.CASCADE, blank=True, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True) address = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) invoice_id = models.CharField(unique=True, max_length=6, null=True, blank=True, editable=False) invoice_date = models.DateField(_("Date"), default=datetime.date.today) invoiced = models.BooleanField(default=False) class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, blank=True, null=True) description = models.CharField(max_length=100) unit_price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.DecimalField(max_digits=8, decimal_places=2, default=1) vat = models.CharField(max_length=250) total = models.CharField(max_length=250) views.py def create_invoice(request): form = InvoiceForm(request.POST … -
I want to add a mobile number field to auth_user in postgres using django and I have no idea on how to proceed as i am a beginner
I am using my own login form with fields firstname lastname email mobile password confirmpassword. The auth_user has all fields except mobile number which i want there. And also what happens on importing User and Auth from django.contrib.auth.models. It would be helpful if u explain in code. -
Setting a form field to the object id in Django's DetailView
Let me explain my problem using some code: I am writing a simple blog application. I have a Post ListView, which lists the blog posts (obviously), and a DetailView which shows the content of the selected post. The DetailView uses the default keyword object to reference the post instance shown in the DetailView. There is a comment section at the end of each blog post. In forms.py I have a CommentForm class: class CommentForm(ModelForm): class Meta: model = Comment fields = ['author_nickname', 'content'] And in models.py I have a Comment model: class Comment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author_nickname = models.CharField(max_length=10) date_posted = models.DateTimeField(auto_now_add= True) content = models.TextField(max_length=90) post = models.ForeignKey(Post,on_delete=models.CASCADE) I use a DetailView to show the content of the selected post, but since it also has a form for adding comments to the comment section, it inherits from DetailView and FormView, like so: class PostDetailView(DetailView, FormView): model = Post form_class = CommentForm success_url = '/thanks/' def form_valid(self, form): form.save() return super().form_valid(form) Now, here is the rub: I want the CommentForm to add a comment to the post that is shown by the DetailView, where the form is (obviously). I've added the form tag at the end of the … -
Cell autoheight when rendering from ods to xlsx
I render .ods-templates to .xslx via templated-docs library. Libreoffice version 6.4.4.2. Template is on github (file ivolga_template.ods). The main problem is that information in cells are not authheighted. When one view rendered file in OpenOffice or MS Excel there only two lines seen (file events_report.xlsx). Whatever I have done (wrap text, optimal height) nothing helped. May be you could say what's wrong with it?.. -
Formset not showing in Django 3
i am creating invoice and items using formset , the problem is the forms is not showing in the templates here is the code : here is the models , forms views and template ##### Models ###### class Invoice(models.Model): invNo = models.CharField(max_length=255,null=True) supplier = models.ForeignKey(Supplier,on_delete=models.CASCADE,null=True,blank=True) branch = models.ForeignKey(Branch,on_delete=models.CASCADE,null=True,blank=True) invTotal = models.DecimalField(max_digits=5, decimal_places=2) invStatus = models.CharField(max_length=200 ,choices=invStatus,null=True,blank=True,db_index=True) attachment = models.FileField(upload_to='invoices/', max_length=100, null=True,blank=True) note = models.TextField(blank=True) history = HistoricalRecords() def str(self): return self.rinvNo class Items(models.Model): Invoice = models.ForeignKey(Invoice,on_delete=models.CASCADE,null=True,blank=True,db_index=True) item = models.CharField(max_length=255,null=True) price = models.DecimalField(max_digits=5, decimal_places=2,default="0.00") q = models.PositiveIntegerField(verbose_name="Quantity") location = models.CharField(max_length=255,null=True,blank=True) status = models.CharField(max_length=200 ,choices=itemStatus,null=True,blank=True,db_index=True) roomNo = models.PositiveIntegerField() qr = models.CharField(max_length=255,null=True) term = models.CharField(max_length=200 ,choices=term,null=True,blank=True,db_index=True) cat = models.CharField(max_length=200 ,choices=cat,null=True,blank=True,db_index=True) reason = models.TextField(max_length=255,null=True) history = HistoricalRecords() def str(self): return self.item ###### Forms ###### class ItemsForm(forms.ModelForm): class Meta: model = Items exclude = () ItemsFormSet = inlineformset_factory(Invoice, Items, form=ItemsForm,fields=['item', 'price'], extra=1, can_delete=True) class InvoiceForm(forms.ModelForm): class Meta: model = Invoice exclude = () def __init__(self, *args, **kwargs): super(InvoiceForm ,self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('invNo'), Field('supplier'), Fieldset('Add Item', Formset('Items')), Field('note'), HTML("<br>"), ButtonHolder(Submit('submit', 'save')), ) ) class InvoiceForm(forms.ModelForm): class Meta: model = Invoice exclude = () def __init__(self, *args, **kwargs): … -
Django - url scheme for nested relationship
I have 3 models: Student, Macro and LTO. Student and Macro have a ManyToMany relationship though table MacroAssignement, and LTO has a OneToOne relationship with MaroAssignement. I need to fetch from the api each LTOs related to the same MacroAssignement (so, each LTOs of a given Macro related to a given Student). The http GET method would use a url like so 'http:localhost:8000/myapp/students/student_id/macro/macro_id/lto/lto_id' ( for example 'http:localhost:8000/myapp/students/1/macro/2/lto/3'. I'm struggling with the url configuration. Here's my current urls.py macro_router = routers.DefaultRouter() macro_router.register(r'macro/(?P<pk2>[0-9]+)/lto/', LTOViewSet) router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') router.register(r'students', StudentViewSet) router.register(r'macro', MacroViewSet, basename='macro') urlpatterns = [ re_path('^', include(router.urls)), ] To clarify, the 'macro' segment inside router, linked to MacroViewSet, is used to access Macro objects as independent entities (performing CRUD operations on it), not yet related to any Student. On the contrary, 'macro' segment in macro_router refers to a particular macro of a given Student. Basically I'm using the same approach of this previous post, but when I try to connect to the api I get the following error: django.core.exceptions.ImproperlyConfigured: "^macro/(?P<pk>[0-9]+)/lto//(?P<pk>[^/.]+)/$" is not a valid regular expression: redefinition of group name 'pk' as group 2; was group 1 at position 31 I don't know how to set up my urls