Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Expected string or bytes-like object error while saving a form/object in Django
When I try to save an object after fetching data from request, it throws an error. Below is my code : obj = BaseUser(contact_no=request.POST.get('contact_no'), location=request.POST.get('location') , bio=request.POST.get('bio') , owner_name=request.POST.get('owner_name') , no_of_employees=request.POST.get('no_of_employees') , date_of_est=request.POST.get('date_of_est') , specialization=request.POST.get('specialization') , sub_category=request.POST.get('sub_category') , skill_1=request.POST.get('skill_1') , skill_1_percent=request.POST.get('skill_1_percent') , skill_2=request.POST.get('skill_2') , skill_2_percent=request.POST.get('skill_2_percent') , skill_3=request.POST.get('skill_3') , skill_3_percent=request.POST.get('skill_3_percent') , instagram=request.POST.get('instagram') , facebook=request.POST.get('facebook') , linkedin=request.POST.get('linkedin') , twitter=request.POST.get('twitter') , profile_complete=True , design_points=0 , otp=0 , user=user , date_of_join=date.today , profile_view=0 , rating=0 , rating_count=0) if 'display_name' in request.POST: obj.display_name = request.POST.get('display_name') elif 'company_name' in request.POST: obj.display_name = request.POST.get('company_name') else: name = str(request.POST.get('first_name') + ' ' + request.POST.get('last_name')) obj.display_name = name form = UserForm(request.POST, files=request.FILES, instance=obj) if form.is_valid(): form.save() and this is my model : class BaseUser(models.Model): display_name = models.CharField(max_length=30, default=None, unique=True) image = models.ImageField(default=None) design_points = models.PositiveIntegerField(default=0) user = models.OneToOneField(User, default=None, on_delete=models.CASCADE) date_of_join = models.DateField(default=date.today) contact_no = models.CharField(max_length=15, default=None, unique=True) location = models.CharField(max_length=50, default=None, choices=LOCATIONS) profile_complete = models.BooleanField(default=False) otp = models.CharField(default=None, max_length=10, null=True, blank=True) bio = models.TextField(default=None, null=True, blank=True) owner_name = models.CharField(max_length=30, default=None, null=True, blank=True) no_of_employees = models.PositiveIntegerField(default=1, null=True, blank=True) date_of_est = models.DateField(default=None, null=True, blank=True) specialization = models.CharField(max_length=50, default=None, choices=SERVICES, null=True, blank=True) sub_category = models.CharField(max_length=50, default=None, choices=SUBSERVICES, null=True, blank=True) profile_view = models.PositiveIntegerField(default=0, null=True, blank=True) rating = models.PositiveIntegerField(default=None, null=True, blank=True) rating_count = … -
Django rest framework serializer for membership Model?
How do I use Serializer for something like This class Language(BaseModel): name = models.CharField(null=False, blank=False, unique=True, max_length=150) class Helper(BaseModel): languages = models.ManyToManyField('Language', blank=True, through="HelperLanguage") class HelperLanguage(BaseModel): helper = models.ForeignKey('Helper', on_delete=models.CASCADE) language = models.ForeignKey('Language', on_delete=models.CASCADE) read = models.BooleanField() write = models.BooleanField() speak = models.BooleanField(default=True) class LanguageSerializer(ModelSerializer): class Meta: model = Language fields = ["id", "name"] class HelperLanguageSerializer(ModelSerializer): language = LanguageSerializer(read_only=True) class Meta: model = HelperLanguage fields = ["id", "language", "read", "write", "speak"] class HelperPublicSerializer(ModelSerializer): languages = HelperLanguageSerializer(source='language', read_only=True, many=True) class Meta: model = Helper fields = ['id', 'languages'] while using HelperPublicSerialiser for list view I am getting error Got AttributeError when attempting to get a value for field read on serializer HelperLanguageSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Language instance. I do understand the problem but couldn't find any solution probably not using membership model right way. -
how i can set middleware for some views in django?
i have a django project with 50 url (in 1 application). i would set a custom middleware for 20 urls. when add middleware to MIDDLEWARE_CLASSES , this set for all urls . How should this be done? (i use last version of python and djnago) -
What views.function does in Django?
This has bothered me for a while now. I've learnt that when you define a URL path in the urls.py file of an application, like this # This is urls.py file for my application. from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:flight_id>", views.flight, name="flight"), path("<int:flight_id>/book", views.book, name="book") ] you pass an argument of the form views.function where function is something you defined in the views.py file: # All my views in views.py of my flights app. def index(request): return render(request, "flights/index.html", { "flights": Flight.objects.all() }) def flight(request, flight_id): flight = Flight.objects.get(pk=flight_id) return render(request, "flights/flight.html", { "flight": flight, "passengers": flight.passengers.all() }) def book(request, flight_id): if request.method == "POST": flight = Flight.objects.get(pk=flight_id) passenger = Passenger.objects.get(pk=int(request.POST["passenger"])) passenger.flights.add(flight) return HttpResponseRedirect(reverse("fligth", args=(flight.id))) I'm curious to know what views.book actually does behind the scenes because it looks very similar to a function call, and it does invoke the function book() I've defined in views.py, but still is missing the paranthese which is representative of a function call. I'm quite confused. -
Problem linkifying column with django-tables 2, can't set custom url
I have one model, for which I have defined 2 tables 2 in tables.py for use with Django-tables2. This is so I can display 2 different tables showing different information in each table. As such, I have two different for each table view, all of which is working fine. I also have two different detail pages I want to link from, for each view. I have a basic model like this: class Customer(models.Model): email = models.EmailField(max_length = 254) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) so my tables.py is, including my attempt to link a column: class CustomerViewTable(tables.Table): first_name = tables.LinkColumn("managecustomer", args=[A("id")]) class Meta: model = Customer template_name = "django_tables2/bootstrap.html" fields = ("id", "first_name", "last_name") If I simply set first_name = tables.Column(linkify=True) and define get_absolute_url in my model, this works, but this won't work when I need two different urls depending on what table is being shown. I want to be able to link to a viewcustomer view or a managecustomer view and pass the id field. Is there a way to define get_absolute-url to use the view it is being called by? Otherwise, when I try the above method shown in my tables.py, I get a NoReverseMatch error, specifically Reverse … -
Why is Django not updating my database with a new field despite deleting it and making migrations?
The issue I'm having is that the DateField I added to my model isn't being updated in the database. If I try retrieving my model's values with Ticket.objects.values(), I receive the exception Column 'date' does not exist. Why is this, and what can I do to force insert it in the database? This happens semi-frequently when I add a new field. I use to solve this by simply deleting the database and migration files. However, that method is not working this time. I've spent an hour covering my bases trying to figure out where it doesn't exist, so it's possible this may be a bug. Here are the steps I've taken: Deleted 0001_initial.py (and all other migration files) Deleted db.sqlite3 Performed migration steps in console like so: python manage.py flush (err'ing on the safe side) >>> yes python manage.py makemigrations python mangae.py migrate python manage.py shell >>> from log.models import Ticket >>> Ticket.objects.values() "Column 'date' does not exist" Examined the newly created database using the sqlite3 command line, and did in fact observe that all of my fields exist except for the 'date' field I want. (The only contradiction I can see is that my newly created migration files do … -
wagtail set auto focal-point during upload
I notice we can set custom image model on wagtail here: https://docs.wagtail.io/en/v2.9/advanced_topics/images/custom_image_model.html I am trying to add an automated focal point during upload max max 200*220px. I tried a lot following its above documentation. from django.db import models from wagtail.images.models import Image, AbstractImage, AbstractRendition class CustomImage(AbstractImage): # Add any extra fields to image here # eg. To add a caption field: # caption = models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields + ( # Then add the field names here to make them appear in the form: # 'caption', ) class CustomRendition(AbstractRendition): image = models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together = ( ('image', 'filter_spec', 'focal_point_key'), Can anyone please help me get it done setting up custom focal point? Thanks Anamul -
/token endpoint not found after adding custom ConvertTokenView
I use rest_framework_social_oauth2 to implement mobile auth features. After I added ConvertTokenView subclass with custom endpoint, /token endpoint of rest_framework_social_oauth2.urls started to return 404. How can I make /token endpoint started to work again? from rest_framework_social_oauth2 import views from oauth2_provider.models import AccessToken from rest_framework.response import Response class ConvertTokenWithUserView(views.ConvertTokenView): def post(self, request, *args, **kwargs): response = super(ConvertTokenWithUserView, self).post(request, *args, **kwargs) token = AccessToken.objects.get(token = response.data['access_token']) user = token.user return Response( { 'access_token' : response.data['access_token'], 'refresh_token': response.data['refresh_token'], 'user_id' : user.pk } ) path('api/custom-auth/', include('mysite.api.urls')), path('api/auth', include('rest_framework_social_oauth2.urls')), -
Django messages not showing up on contact form template
I have a contact form on my Django Site. I am attempting to have a message box popup when the user clicks to submit their message. For some reason, I cannot get the message I am creating to display. I have looked everywhere but cannot seem to find a solution. I have ensured all steps to enable messages in the docs have been met. https://docs.djangoproject.com/en/3.0/ref/contrib/messages/ Any help suggestions would me much appreciated! views.py from django.shortcuts import render # add to the top from .forms import ContactForm # new imports that go at the top of the file from django.core.mail import EmailMessage from django.shortcuts import redirect from django.template.loader import get_template from django.contrib import messages import global_admin nickname = global_admin.nickname # our view def contact(request): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('contact/contact_template.txt') context = { 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content, } content = template.render(context) email = EmailMessage( "New contact form submission", content, "email@email.com", ['email@email.com'], headers={'Reply-To': contact_email } ) email.send() messages.debug(request, 'Thanks for reaching out! We … -
Sending Emails from Django after executing an order for E-commerce Not Working
I am trying to send an email to the user who has just complete a purchase transaction for an e-commerce project. I have previously configured email to be sent from Django and it was successful for other parts of the project such as newsletter email and password update emails but in this section, it is a little bit more complex, I don't know why I am not receiving emails and no error message is appearing to know how to fix it. My question is: How to fix this and arrange an email to be sent after a purchase is made. I have searched for ways to send emails from Django but this is the one I found, is there an easier way to send email from Django. Here is the Views.py class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False } return render(self.request, "payment.html", context) else: messages.warning( self.request, "You have not added a billing address") return redirect("core:checkout") def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.grand_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = … -
How do I automate a python script to run every hour in a Django website hosted on Heroku?
My project involves a Django website using data from a .csv file generated from a web scraping script, which needs to be hosted on Heroku. My development OS is Windows 10. When my development server is run, it initially executes the script under the main application's views.py file: exec(open('homepage/scrape.py').read()) where homepage is the name of the main application of the project and scrape.py is the web scraping script. What I need to occur is for this scrape.py to run every hour and be able to work on both a Heroku dyno and my Windows development environment. Thanks. -
Calculating Total Price from related django objects
Model A has fields, Item and Price Model B has fields, Item and Quantity I want to get total spent i.e. price* quantity whenever b.field = a.field in django P.S - Model B has a foreign key as items of model A Thanks -
Date, time booking system Django
I'am creating a hairdresser website using Django. I have a question about the database conception. I have in my models.py : class Service(models.Model): service= models.CharField(max_length = 100, unique=True) class Booking(models.Model): firstNameUser = models.CharField(max_length=50) nameUser = models.CharField(max_length=50) email = models.EmailField(max_length=254, null = True) telephone = models.CharField(max_length=14, null = True) service= models.ForeignKey(Service, related_name ="reservation_service", on_delete = models.PROTECT) I have a question about the appointment. I have created a form in the forms.py: class DateInput(forms.DateInput): input_type = 'date' class BookingForm(forms.ModelForm): first_name = forms.CharField(max_length=50, label="", widget=forms.TextInput(attrs={'placeholder':'Votre prénom'})) last_name = forms.CharField(max_length=50, label="", widget=forms.TextInput(attrs={'placeholder':'Votre nom'})) email = forms.EmailField(label="", widget=forms.TextInput(attrs={'placeholder':'Your email'})) phone = forms.CharField(max_length=10, label="", widget=forms.TextInput(attrs={'placeholder':'Your phone number'})) service= forms.ModelChoiceField(queryset=get_all_services(), label="") class Meta: model = Booking fields = ['first_name', 'last_name', 'email', 'phone', 'service'] I want to add in my form a date and a time for the appointment. Indeed, the dates and the times must be available. So, if the date is available, then, the user can choose from the available times. I want to know how can I make this work? Should I create another table in my models.py for example class DateTimeBooking(models.Model): date = models.DateField(default=timezone.now) time = models.TimeField(auto_now=False, auto_now_add=False) And then I link the DateTimeBooking table to the Booking table with a foreign key ? … -
my SignUp form is not submitting in django
i used django-allauth and i found out that i need to add some more fields to the Sign Up form,so i did add some more fields to the Forms.py,now everything is working fine not until i tried to submit the form and i get redirected back to the signup page without submitting or saving the request nor giving me an error please help here is my forms.py and in there are the additional fields i want Forms.py class MyCustomSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(MyCustomSignupForm, self).__init__(*args, **kwargs) self.fields['First_name'] = forms.CharField(required=True) self.fields['Last_name'] = forms.CharField(required=True) self.fields['Phone_number'] = forms.IntegerField(required=True) self.fields['Servives'] = forms.BooleanField(required=True) self.fields['Payment_Mode'] = forms.CharField(required=True) self.fields['City'] = forms.CharField(required=True) self.fields['Servives'] = forms.CharField(required=True) def save(self, request): First_name = self.cleaned_data.pop('First name') Last_name = self.cleaned_data.pop('Last name') Phone_number = self.cleaned_data.pop('Phone number') Servives = self.cleaned_data.pop('Servives') Payment_Mode = self.cleaned_data.pop('Payment Mode') City = self.cleaned_data.pop('City') user = super(MyCustomSignupForm, self).save(request) -
How to login and return the authenticated object, I am unable to return the full Django Rest Framework object
I am able to carry out the authentication of the school object through the user and password but I would like to return the complete school object, including with the object id how to solve? School serializer class Serializer class EscolaSerializer(serializers.ModelSerializer): class Meta: model = Escola fields = ( 'id', 'nome', 'endereco', 'diretor', 'cnpj', 'telefone', 'email', 'tipo', 'user', 'criacao', 'senha' ) Login Escola serializer class Login Escola class LoginEscolaSerializer(serializers.ModelSerializer): user = CharField(required=False, allow_blank=True) senha = CharField(required=False, allow_blank=True) class Meta: model = Escola fields = ( 'user', 'senha', 'id' ) def validate(self, data): user = data.get("user", None) senha = data.get("senha", None) validacao = Escola.objects.filter( Q(user=user), Q(senha=senha) ) if validacao.exists() and validacao.count() == 1: validacao = validacao.first() else: raise ValidationError("Usuario ou senha incorreto") Login Escola view Views class LoginEscolaViewAPIView(APIView): permission_classes = [AllowAny] serializer_class = LoginEscolaSerializer def post(self, request, *args, **kwargs): data = request.data serializer = LoginEscolaSerializer(data=data) serializer_class = EscolaSerializer() if serializer.is_valid(raise_exception=True): new_data = serializer_class.data, return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -
django - generate CREATE TABLE sql for models
Is there any way in django to generate the CREATE TABLE script for my models for a particular DB engine? (MySQL in my case) -
Django - render relevant value from queryset in template
I am rendering data from my views into my template, as follows: <tbody> {% for item in lyrics %} <tr class='lyrics-table'> <td>{{item}}</td> <td> {% if item in user_flash %} <p>{{flash_answer}}</p> {% else %} <p>xxx</p> {% endif %} </td> My views are as follows: class SongVocab(LoginRequiredMixin, generic.DetailView): model= models.Song template_name = 'videos/song_vocab.html' context_object_name = 'song' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) from pymystem3 import Mystem m = Mystem() user_flash = Flashcard.objects.filter(owner=self.request.user).values_list('question', flat=True) lyrics_list = models.Song.objects.get().lyrics_as_list() user_flash_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(user_flash))] user_flash_clean = [w for w in user_flash_ if w.strip()] ##removes empty strings lyrics_list_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(lyrics_list))] lyrics_list_clean = [w for w in lyrics_list_ if len(w.strip())] user_word = list(set(user_flash_clean) & set(lyrics_list_clean)) import icu # PyICU def sorted_strings(strings, locale=None): if locale is None: return sorted(strings) collator = icu.Collator.createInstance(icu.Locale(locale)) return sorted(strings, key=collator.getSortKey) context['percent_known'] = ((len(user_word))/(len(set(lyrics_list_clean))))*100 context['lyrics'] = sorted_strings(set(lyrics_list_clean),"ru_RU.UTF8") context['user_flash'] = user_flash_clean context['flash_answer'] = [] for word in user_word: flash = Flashcard.objects.get(owner=self.request.user, question=word) context['flash_answer'].append(flash.answer) return context My question is: how can I render the relevant flash_answer for every user_word in my template? At the moment, I get the entire queryset, which makes sense, because that is what flash_anwswer is. But the two are linked, … -
Django - you have an error in your sql syntax
I'm trying to execute a simple MySQL query that will work on MySQL, while it gives any kind of error on Django. Here is the query: Summary = myTable.objects.raw("select FROM_UNIXTIME(unixtime, '%%Y/%%m/%%d') as ndate,count(id) as query_count from myTable group by ndate order by query_count DESC") This line will give me the following error: Raw query must include the primary key But if i edit the query to the following: select id FROM_UNIXITIME.... I will get the following error: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(unixtime, '%Y/%m/%d') as ndate,count(id) as query_count from myTable' at line 1") And here is my model: class myTable(models.Model): user_id = models.IntegerField() username = models.CharField(max_length=150) query = models.CharField(max_length=100) unixtime = models.IntegerField() class Meta: managed = False db_table = 'mytable' The query, basically, should only count how many rows there are for this table every day and give the following output: {'2020/06/28': 30, '2020/06/27': 20 ... }. Can anyone help me out on how to make the query work, or at least how to do the same query but using the Django ORM, since using raw queries is being … -
Error adding GinIndex to model in Django with Postgres
I am trying to add GinIndex to my model however, I am getting an error when migrating: django.db.utils.ProgrammingError: data type character varying has no default operator class for access method "gin" HINT: You must specify an operator class for the index or define a default operator class for the data type. This is my model: class Post(models.Model): title = models.CharField(max_length=100) guid_url = models.CharField(max_length=255,unique=True, null=True) content = models.TextField(validators=[MaxLengthValidator(1200)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) last_edited= models.DateTimeField(auto_now=True) tags = TaggableManager(help_text="Tags", blank=True) likes= models.ManyToManyField(Profile, blank=True, related_name='post_likes') class Meta: indexes = [ GinIndex(fields=['title','content'],name='search_idx_post') ] I was wondering what is causing this issue I cannot find how to resolve this issue. Thanks in advance! -
How to debug Django custom management command using VS Community?
I am trying to debug a custom management command using Visual Studio Community. I run my command by starting a PowerShell session for my current environment. I do this from Solution Explorer by right-clicking "Python Environments", selecting "View All Python Environments", clicking on my environment, and then in the details panel below clicking "Open in PowerShell". I then type the following command into Powershell: python manage.py name_of_management_command This causes the script to run, but since VS doesn't know about it, the debugger is not triggered, so I can't set breakpoints or do other common tasks. I found a related question that addresses how to do this in Visual Studio Code, but that solution doesn't work in the VS client. Or, at least, I can't find documentation explaining how to do a comparable thing. Does anybody know a way to do this? I would like be able to either start the management command from inside VS so that VS knows about it, or find a way to trigger VS from the command line. -
How to save groups in a user using rest framework - Django?
I have a serializer with registration information. The data of the request.data is complete, right after validating the validated_data shows the empty group. class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id',) class serializerUser(serializers.Serializer): Meta: Group id = serializers.PrimaryKeyRelatedField(read_only=True) first_name = serializers.CharField() last_name = serializers.CharField() email = serializers.CharField() cpf = serializers.CharField() token_user_chain = serializers.CharField() telefone = serializers.CharField() groups = GroupSerializer(many=True) observacao = serializers.CharField(allow_null=True, allow_blank=True) password = serializers.CharField(write_only=True) username = serializers.CharField(write_only=True) password_again = serializers.CharField(write_only=True) def create(self, validated_data): print(validated_data) Print request.data {'first_name': 'Marcelo', 'last_name': 'Wanderley', 'username': 'marcelo', 'cpf': '1234', 'telefone': '99999999', 'email': 'marceloa@teste.com', 'observacao': '', 'groups': [{'id': 2}], 'password': '111111', 'password_again': '111111', 'token_user_chain': 'TMWTIeGs2t1YPpKke2RZh2tLVMuMWdLFxaFYdD', 'private_key': ''} Print validated_data OrderedDict([('first_name', 'Marcelo'), ('last_name', 'Wanderley'), ('email', 'marceloa@teste.com'), ('cpf', '1234'), ('token_user_chain', 'TMWTIeGs2t1YPpKke2RZh2tLVMuMWdLFxaFYdD'), ('telefone', '999999'), ('groups', [OrderedDict()]), ('observacao', ''), ('password', '111111'), ('username', 'marcelo'), ('password_again', '111111')]) In the print of the request.data we have the group id In the print of valideted_data the group field is empty. -
hyperlinks blocked on opening as a new tab - django
I have a python script (A.py) that accepts users input via form and runs another python script (B.py). B.py stores html formatted results into a folder named yyyymmdd. The file generated by B.py is like "results_hhmmss.html", so every time B.py script is executed a new has html file is created. As per my urls.py code below, visiting 127.0.0.1:8888 takes me to home_page. Further, once i submit form using a button in the home_page, the scripts gets executed successfully and a result file is generated. I am not sure how to render the results as the results file name keeps varying. Hence, i tried keeping a constant page results.html and add a hyper-link to file results_hhmmss.html within results.html. I tried providing href= with absolute path of results_hhmmss.html file and the hyperlink can be seen when hovered pointing to file:///Users/msh0047/tmp/welcome/20200627/results_231603.html However, upon clicking the hyperlink, nothing happens. When I open the hyperlink in a new tab, i see blank page with "about:blank#blocked" in the address bar. I also tried providing href= with relative path of the results_hhmmss.html file and the hyperlink can be seen when hovered pointing to http://127.0.0.1:8888/20200627/results_231603.html , clicking the hyperlink throws error saying Page not found(404) and The current … -
Showing a generated document using django
I have a Django site and want it so that when the user presses a button on the site that a python file makes a word document and shows it to the user in the browser. I am getting an error saying that context must be a dict rather than set. my document seems to be made in my pycharm project folder but it doesn't want to show itself for some reason. my process is as follows: user clicks a html button. urls.py then points the browser to a function in my view.py called making_the_doc. This making_the_doc function runs a function in my the plot.py file which will generate the document and returns it to view.py for presentation to the user. Firstly i created the code that will generate the document. This file is known as theplot.py. THEPLOT.PY def making_a_doc_function(request): doc = docx.Document() doc.add_heading('hello') doc.save('this is doc.docx') generated_doc = open('this is doc.docx', 'rb') response = FileResponse(generated_doc) return render(request, 'doc.html', {response}) Then I linked this function to my views.py VIEWS.PY def making_the_doc(request): return making_a_doc_function(request) Then i created my url paths to point to the views.py URLS.PY path('making_a_doc', views.making_the_doc, name='doc'), finally I generate my html button so the whole process can start … -
Overriding Django Model fields when accessed via get or related
I'm building a site that has web pages for TV Shows and Networks. A TV Show can be independent, or part of a network. Each page can be assigned a background_color class Page(models.Model): type = models.CharField(max_length=1, choices=TYPE_CHOICE, default=TVSHOW) network = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) background_color = models.CharField(max_length=6, null=True, blank=True) When the page is loaded, the background color should be set. If the TV Show isn't associated with a network, it should use it's BG Color. If it does have a related network, it should use the networks BG Color. Looking at this question, here's what I came up with: class PageQuerySet(models.query.QuerySet): def get(self, **kwargs): page = super().get(**kwargs) if page.network: network = page.network fields_to_override = [ 'background_color', ] for field in fields_to_override: setattr(page, field, getattr(network, field)) return page class Page(models.Model): objects = PageQuerySet.as_manager() type = models.CharField(max_length=1, choices=TYPE_CHOICE, default=TVSHOW) network = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) background_hex_color = models.CharField(max_length=6, null=True, blank=True) This actually works perfectly when the object is fetched via get (obviously), but when it's fetched as a related object of the Episode model (episode.page), it uses the TV Show background color. I looked at the Base Manager docs, but don't understand them. When I set this manager to be used as … -
I started a Django project with all requirements but static files can't load successfully
i'm working on python 3.8.3, pip 20.1.1, django 3.0.6 and virtual envirnment are already installed but i'm not getting the style from my css files and the behavior from javascript onto my web page and here is the photo of errors in my console in my settings I configured well all about the static file and the template and the following is my settings.py STATICFILES = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') and that's also the the urls for the whole projects urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('estate_web.urls')) ] and I done well all about the url configuration and the following is my app url urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home') ] and that's the views which return the page views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'index.html') i don't if there is any error in my codes but I can't get the website as I expected and i wan't to know if there is any fixation of this because I met with it couple times