Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-mailer customizing admin area
When using django mailer (https://github.com/pinax/django-mailer) I realized that the default tables added to the admin area (such as Message logs and Messages) did not add the message_log field which indeed is available if one looks at the tables that are added. Since the error message is very valuable to me I wanted to add it, and simply added the "log_message" to the app's MessageLogAdmin like this: class MessageLogAdmin(MessageAdminMixin, admin.ModelAdmin): list_display = ["id", show_to, "subject", "message_id", "when_attempted", "result", "log_message"] list_filter = ["result"] date_hierarchy = "when_attempted" readonly_fields = ['plain_text_body', 'message_id'] search_fields = ['message_id'] However, is there really no other way to customize the admin area for django-mailer other than modifying the source code? E.g through settings.py -
Success_url = "detail/int:pk"
class EditBlog(UpdateView): model = Entry template_name = 'entry/edit.html' success_url = "/" fields = ['entry_title', 'entry_text'] def form_valid(self, form): form.instance.entry_author = self.request.user return super().form_valid(form) i want to put in my success URL the name of the path because the URL of my detail page has a PK with it and it's not working the way i want -
django circular import in models
I understand I have a circular import here, but one of them is being used to define some foreign key fields and the other is only there for a property in the other model. models: receipts/models.py from django.db import models from employees.models import Employee class Receipt(models.Model): Supervisor = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='receipt_supervisor') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='receipt_employee') amount = models.DecimalField(max_digits=6, decimal_places=2) employees/models.py from django.db import models from receipts.models import Receipt class Employee(models.Model): number = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) @property def receipt_sum(self): receipts = Receipt.objects.filter(Employee=self.pk) sum = 0 for receipt in receipts: sum += receipt.amount return sum I get this error: cannot import name 'Employee' from partially initialized module 'employees.models' (most likely due to a circular import) Is there a way I can get around this so that I can do the receipt query in the Employee property? Or do I need to do this calculation elsewhere? Thanks! -
How load (server-side) localhost webpage from web server?
How can I load a web page running on http://localhost:9001 from my website on http://localhost:9000? Currently the website loads the client's localhost. -
understanding memory in jsonb based querysets (to write to file)
I am trying to write a Django queryset to a file and although it works, it consumes a LOT of RAM and I am not able to write out the entire field values because it runs out of memory. Let me explain my setup: instance_model=SomeModel.objects.all().order_by('created_at') print(instance_model()) # outputs 1million or so entries Now, I start to write out the field values I am interested in like so: with open("write_prices.dat", 'w') as file_handler: for item in prices_model: for each_item in item.prices: #prices is a JSONB field if each_item['symbol']=="PS2": file_handler.write("{}\t{}\n".format(\ item.utc_timestamp['utc_time'],\ each_item['price'])\ ) my models.py looks like so: class SomeModel(TimeStampedModel, AbstractPS2Model): prices = JSONField(blank=True,default=dict) utc_timestamp = JSONField(blank=True,default=dict) def __str__(self): return self.uuid When I try to write out the fields in prices I am interested in, I am hardly able to iterate through 15k or so DB entries - before the script gets killed because of OOM. I assumed everything was a generator and I did not have to worry about memory, but obviously my understanding seems wrong. I think I am doing something super silly here, but I am not able to figure out what :( -
Django and celery DatabaseError: DatabaseWrapper
I build a scraper and the price needs to be updated every 12 hours or so and i use celery to do it, but i get an error after the task is received: django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with al ias 'default' was created in thread id 48931120 and this is thread id 89001448 @shared_task def update_price(): scraper = Scraper.objects.all() for i in scraper: price = amazon_scraper(i.link) i.update(last_price = price, last_checked = timezone.now()) time.sleep(18) /settings.py CELERY_BEAT_SCHEDULE = { 'update_price': { 'task': 'hackaton.tasks.update_price', 'schedule': datetime.timedelta(seconds=120), }, } -
How to display manytomany field in django admin with a related model in a user-friendly way?
I'm struggling to display a manytomany field in the admin with the related model in a user-friendly manner. The project is already up and running so adding a through table is not preferred. The set-up is something along these lines; class User(AbstractUser): is_member_of_organization = models.ManyToManyField(Organization, blank=True, verbose_name=_("is member of organization(s)"), related_name='orgmembers') class Organization(models.Model): name = models.CharField(max_length=60, verbose_name=_("organization name")) the only reasonable way I manage to display the related users with organization admin is via a TabularInline admin.py class UserOrgAdminInLine(admin.TabularInline): model = User.is_admin_for_organization.through extra = 0 @admin.register(Organization) class OrganizationAdmin(admin.ModelAdmin): inlines = (UserOrgAdminInLine,) However, looking up users is not convenient as soon as their number increases. I would like something similar to filer_horizontal but I am not sure how to include it directly in the OrganizationAdmin admin class. Furthermore, I am using fieldsets (which I believe should have no special rules or syntax to it compared to ordinary fields = . One little subquestion - in the tabular inline, when I use only model = User django throws an error that there is no foreign key to it, but when I use the additional .is_admin_for_organization.through it works, but there is no through table and I though that this work just in that … -
initialize modelform fields with url parameters in cbv
I have a cbv create view that displays a modelform. I want to preselect a foreignkey field which is displayed as select choice field. My problem is that kwargs.get('building_id') in modelform returns None class VlanCreateForm(ModelForm): class Meta: model = Vlan fields = ['number','description','network','building'] def __init__(self, *args, **kwargs): building_id = kwargs.get('building_id') super().__init__(*args, **kwargs) self.fields['building'].initial = building_id building is a foreign key to buildings. If I put a constant like self.fields['building'].initial = 1 it is working class VlanCreateView(CreateView): model = Vlan form_class = VlanCreateForm and the url is vlan/building/<int:building_id>/create so I call it like vlan/building/1/create -
Django Serializers running slow to convert JSON
I have 5 different Foreign Key values in 1 model. There are 1800 records in total. Using AJAX it is necessary to convert the data to JSON format. I can do this with the Serializers library. I use use_natural_foreign_keys = True for Foreign Key values to return string values. use_natural_foreign_keys = True When i use it; 15 seconds of query When I am not using it; 0.5 second But I have to use it. Otherwise, I cannot get Foreing Key values when converted to JSON format. I leave the query here. How can I make queries faster? Thanks in advance. result=AbcModel.objects.all() if kapanan_talepler: jsons=serializers.serialize('json',result, use_natural_foreign_keys=True) -
Django Static Images Not Loading
I have images downloaded in the following path but they refuse to load for me. Any idea what I may have configured incorrectly that is forcing this? C:\Users\xxx\Python\Price Tracking\Django\mysite\polls\static\polls\images stl.jpg chicago.jpg nyc.jpg settings: INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_plotly_dash.apps.DjangoPlotlyDashConfig', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' html: {% load static %} <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="{% static 'polls/chicago.jpg' %}" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'polls/nyc.jpg' %}" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'polls/stl.jpg' %}" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> -
Are you required to make an http request when trying to use Chart.js?
I followed a tutorial video that showed how to set up Chart.js with Django, using Jquery and API function calls to a page on my site. However, I don't need to make these function calls to get the data, as the data are associated with my objects themselves. When I get rid of the http function call and just write the code instead, my graphs don't show up. Is the http format required? A working version I have is: <script> var endpoint = ''/api/chart/data/''; fetch(endpoint, { method: "GET", }).then(response => response.json()) .then( data => { console.log('Success:', data); ... var ctx{{ forloop.counter }} = document.getElementById("myChart{{ forloop.counter }}"); var myChart = new Chart(ctx{{ forloop.counter }}, graph_data); }) .catch((error) => { console.log("Error:") console.log(error); }); </script> <div style="width: 60%; float:left;"> <canvas id= "myChart{{ forloop.counter }}" style = "padding-bottom: 9px;"></canvas> </div> Could this instead just be: console.log('Success:', data); ... var ctx{{ forloop.counter }} = document.getElementById("myChart{{ forloop.counter }}"); var myChart = new Chart(ctx{{ forloop.counter }}, graph_data); <div style="width: 60%; float:left;"> <canvas id= "myChart{{ forloop.counter }}" style = "padding-bottom: 9px;"></canvas> </div> The error I am getting is Chart.min.js:14 Uncaught TypeError: Cannot read property 'length' of null at Object.acquireContext (Chart.min.js:14) at new t.Controller (Chart.min.js:11) at new t (Chart.min.js:12) … -
Django-Haystack not finding any field
I am trying to write a little search engine with django-haystac and whoosh. I adapted their tutorial, I've created my index from and query it succesfully with QueryParser and now I'm trying to use their view. when I try to access the search url at: http://127.0.0.1:8000/my_search/ I get the error: The index 'BookIndex' must have one (and only one) SearchField with document=True. If I remove the search_indexes.py I can access the search page, but then of course it does not work as it doesn't have any index to search. By debugging it it seems it does not pickup any fields, but it does see the class. I tried several things but nothing worked my search_indexes.py: from haystack import indexes from my_search.models import Paper class BookIndex(indexes.SearchIndex, indexes.Indexable): """ This is a search index """ title = indexes.CharField(model_attr='title'), abstract = indexes.CharField(document=True, use_template=False, model_attr='abstract'), def get_model(self): return Paper def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects # .filter( pub_date__lte=datetime.datetime.now()) my models.py: from django.db import models class Paper(models.Model): paper_url = models.CharField(max_length=200), title = models.CharField(max_length=200), abstract = models.TextField() authors = models.CharField(max_length=200), date = models.DateTimeField(max_length=200), def __unicode__(self): return self.title thanks! -
Django Prepopulate ModelForm with Table Record
I am trying to create an Edit for that allows the user to scroll through a table and click a button existing in each row to edit the data within a modal. The issue that I am running into is when I try to prepopulate the form with the existing values. How would I convert the EditCommunicationsForm below to display the current values of the row that you selected edit for? forms.py class CommunicationsForm(forms.ModelForm): class Meta: model = Communications fields = "__all__" widgets = { 'project':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter your Project Name'}), 'title':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter a short Title'}), 'intent':forms.Textarea(attrs={'class': 'form-control','height':'50px','placeholder':'Describe the intent and desired outcome of the communication'}), 'date':forms.TextInput(attrs={'class': 'form-control','placeholder':'Select a Date'}), 'channel':forms.Select(attrs={'class': 'form-control'}), 'content_type':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Content Type'}), 'audience':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter the Audience(s)'}), 'status':forms.Select(attrs={'class': 'form-control','placeholder':'Select the Status'}), } class EditCommunicationsForm(forms.ModelForm): class Meta: model = Communications fields = "__all__" widgets = { 'project':forms.TextInput(attrs={'class': 'form-control','initial':'Project 123'}), 'title':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter a short Title'}), 'intent':forms.Textarea(attrs={'class': 'form-control','height':'50px','placeholder':'Describe the intent and desired outcome of the communication'}), 'date':forms.TextInput(attrs={'class': 'form-control','placeholder':'Select a Date'}), 'channel':forms.Select(attrs={'class': 'form-control'}), 'content_type':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Content Type'}), 'audience':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter the Audience(s)'}), 'status':forms.Select(attrs={'class': 'form-control','placeholder':'Select the Status'}), } views.py def communications(request): comms_list = Communications.objects.order_by('id') if request.method == "POST": new_form = CommunicationsForm(request.POST, request.FILES) edit_form = EditCommunicationsForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('http://127.0.0.1:7000/polls/communications/',{"new_form":new_form,"edit_form":edit_form,'comms_list':comms_list}) else: … -
Expire a token in 24 hours - django-rest-knox
I am using django-rest-knox for token authentication in my Django REST Framework app. What I want is to make the token expire only if 24 hours are passed. Is there any setting that it can make this thing happen. Thanks -
pd.read_sql() takes about 10 seconds to load a 200k row MS SQL Server table in python
My Django API reads a table (150k rows) and perform some operations using that data every time the API is executed. The table is indexed on Type, Ticker, and Date. Type has 2 Distinct values (varchar), Ticker has 30 Distinct values(varchar) and Date has 5040 Distinct values (Datetime). conn = pyodbc.connect(driver='{Driver name}', server='Server Name', database='Database Name', user='user name', password='password') sql = """ Select [Date],[Close],[Ticker],[Type] from [dbo].[Stocks_data]""" df = pd.read_sql(sql,conn) Is there any way to get the data from database in a few milli-seconds or save the table as cache (I don't know much about cache) in the djago application. We update that table daily (Closing prices of the stocks) -
Javascript won't work inside Django for loop form
I'm trying to refactor this code so with this loop I can avoid repetition and scale the code, but the javascript stops working as I put the django loop <ul class="navbar-nav"> <li class="nav-item"> <!-- class="active" --> <a class="nav-link" href="{% url 'stories' %}">{% trans "Stories" %}</a> </li> </ul> <ul class="nav navbar-nav ml-auto"> <li class="nav-item"> <a class='dropdown-toggle' data-toggle='dropdown' role='button' aria-expanded='false'>{% trans "Lingua" %}<span class='caret'></span></a> <ul class='dropdown-menu' role='menu'> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <li> <form name="languagePt" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="pt-br" /> <a href="javascript:document.languagePt.submit()"> <img width='64' height='64' src="{% static 'img/pt-br.png' %}" alt='pt-br'> </a> </form> </li> <form name="languageEn" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="en-gb" /> <a href="javascript:document.languageEn.submit()"> <img width='64' height='64' src="{% static 'img/en-gb.png' %}" alt='en-gb'> </a> </form> </li> {% endfor %} </ul> the code will be almost like that when done, if it's possible to use javascript inside the loop <ul class="navbar-nav"> <li class="nav-item"> <!-- class="active" --> <a class="nav-link" href="{% url 'stories' %}">{% trans "Stories" %}</a> </li> </ul> <ul class="nav navbar-nav ml-auto"> <li class="nav-item"> <a class='dropdown-toggle' … -
Can you use multithreading with Celery?
I'm trying to build an email scrapper, but the problem is that it is very slow to crawl websites one by one. I've been researching how to speed up this process and I came across multithreading, after looking deeper into it, I found that Django has Celery to do it, but I've been reading the docs and haven't found anything. So I have a couple questions: Is it possible to use Celery for multithreading, multiprocessing? How can it be done? With Celery already installed on Django Thank you! Any help would really appreciate it! -
how can I add multiple images of each student using django rest framework
I want to upload multiple images for each student using django rest framework. currently, Im only able to upload one image for each student, but I want to be able to upload multiple images for each student in uploads folder in a directory of their name. Im building a facial attendance recognition system and I need multiple images of each student. here is my models.py file. class Student(models.Model): Name=models.CharField(max_length=200) Enrollment_No=models.CharField(max_length=200) Registration_No=models.CharField(max_length=200) Semester=models.IntegerField() Year=models.CharField(max_length=200) Course_Name=models.CharField(max_length=200) Course_Code=models.CharField(max_length=200) registered_at= models.DateField(auto_now_add=True) def __str__(self): return self.Name class studentImage(models.Model): Name= models.CharField(max_length=200, default='no-name') Student= models.ForeignKey(Student, on_delete= models.CASCADE) image=models.ImageField(upload_to= 'uploads/') def __str__(self): return self.Name class serializers.py file class StudentSerializer(serializers.ModelSerializer): class Meta: model=Student fields="__all__" class studentImageSerializer(serializers.ModelSerializer): class Meta: model= studentImage fields="__all__" views.py file @api_view(['POST']) def studentCreate(request): serializer = StudentSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() else: print('Hello World') return Response(serializer.data) Please let me know what changes should I make to the code, what I should add in the views file to allow multiple images upload of student in uploads directory in a directory of student name -
Wagtail: How to link a model to an Orderable which links to another model
Lets say I have multiple models which require an address e.g. boxing clubs & boxing events. I have considered making the address an abstract and adding the panels everywhere I needed them but figured that creating its own table/model would be cleaner than the address fields being added to each model that needs them. Now, a boxing club has it's own timetable where it can specify on which day it's in session as well as a location should it be in a different club than usual. So, my attempt at a solution looks something like this. class BoxingClub(models.Model): name = models.CharField(max_length=30) panels = [ FieldPanel('name'), InlinePanel('club_timetable', heading='Timetable Information') ] class ClubTimetable(Orderable): _DAYS_OF_WEEK = ( (0, "Monday"), ... (6, "Sunday") ) attached_to = ParentalKey( 'club.BoxingClub', related_name='club_timetable') linked_location = models.ForeignKey( 'location.Address', on_delete=models.SET_NULL, related_name='location_address', null=True) weekday = models.IntegerField( 'Day of training session', choices=_DAYS_OF_WEEK) panels = [ FieldPanel('weekday'), InlinePanel('linked_location', help_text='Sessions location information.') ] class Address(models.Model): address_line_1 = models.CharField( max_length=30, help_text='First line of address.') address_line_2 = models.CharField( max_length=30, null=True, blank=True, help_text='Second line of address.') map_coord_lat = models.CharField( max_length=25, help_text='Comma separated latitude.' ) map_coord_lon = models.CharField( max_length=25, help_text='Comma separated longitude.' ) panels = [ FieldPanel('address_line_1'), FieldPanel('address_line_2'), FieldPanel('map_coord_lat'), FieldPanel('map_coord_lon'), ] This however, gives me the following error: … -
How to automaticaly get user name, who post comment? (I don't want to type name of user manually)
How to automaticaly get user name, who post comment? (I don't want to type name of user manuely) I don't want to be able to change it or to be seen. I tried to do it the same way I do for making new posts, but I guess it is a little more complicated... Here is the code: Views: from . models import Post, Comment from . forms import PostForm, CommentForm class add_comment(CreateView): model = Comment form_class = CommentForm template_name = 'add_comment.html' success_url = reverse_lazy('home') ordering = ['-id'] def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) urls: from . views import add_comment path('details/<int:pk>/comment/', add_comment.as_view(), name = 'add_comment'), models: from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() image = ResizedImageField(size=[480, 320], quality=100, upload_to='pictures', null=True, blank=True) video = models.FileField(upload_to='videos', null=True, blank=True) date = models.DateTimeField(default=datetime.now) def __str__(self): return f'{self.author}: {self.body}' class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date'] def __str__(self): return '%s - %s' % (self.name, self.post.body) forms: from . models import Post, Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } -
Bootstrap and MD Bootstrap Carousel not working in Django
So I am trying to add a simple MD Bootstrap carousel to a django template, however, it only loads the first image and the controls don't work. I followed this article https://mdbootstrap.com/articles/jquery/how-to-integrate-mdbootstrap-with-django/ on how to integrate MD Bootstrap but I have a feeling that some of the imports aren't quite working. I also made sure that other_banner_images is actually querying the images I want. I also tried replacing the MDB Carousel with a regular BS carousel and had the exact same issue. Any help would be greatly appreciated :) Here is the template in question home.html, which I modified from https://mdbootstrap.com/docs/standard/components/carousel/ <!-- Carousel wrapper --> <div id="carouselBasicExample" class="carousel slide carousel-fade" data-mdb-ride="carousel" > <!-- Indicators --> <ol class="carousel-indicators"> <li data-mdb-target="#carouselBasicExample" data-mdb-slide-to="0" class="active"></li> <li data-mdb-target="#carouselBasicExample" data-mdb-slide-to="1"></li> <li data-mdb-target="#carouselBasicExample" data-mdb-slide-to="2"></li> </ol> <!-- Inner --> <div class="carousel-inner"> <!-- Single item --> <div class="carousel-item active"> <img src="{{ default_banner_image.image.url }}" class="d-block w-100" alt="..." /> <div class="carousel-caption d-none d-md-block"> <h5>{{ default_banner_image.text }}</h5> <p>{{ default_banner_image.sub_text }}</p> </div> </div> {% for image in other_banner_images %} <!-- Single item --> <div class="carousel-item"> <img src="{{ image.image.url }}" class="d-block w-100" alt="..." /> <div class="carousel-caption d-none d-md-block"> <h5>{{ image.text }}</h5> <p>{{ image.sub_text }}</p> </div> </div> {% endfor %} </div> <!-- Inner --> <!-- … -
Django create form instance with two relations keys
First of all, I want to make it clear that I start with Django. I've searched a lot on this subject here, but I haven't found the right answer. Here is my problem, I want to create a form (not in the admin) where users of the site can fill in their profiles and addresses What I'm trying to do is fill out two templates with one submission for the user. So far I have managed to save the profile but I can't fill in the address and link it to the profile. Here is my code, hoping you can help me. Thanks in advance my userprofile model class UserProfile(models.Model): user = models.OneToOneField(CoreUser, on_delete=models.CASCADE, verbose_name="Email") address = models.ForeignKey(Address, on_delete=models.PROTECT,related_name='useraddress') first_name = models.CharField(max_length=50, verbose_name="First name user", null=True) last_name = models.CharField(max_length=50, verbose_name="Last name", null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) birthdate = models.CharField(max_length=200, null=True) profile_picture = models.ImageField(default='default.jpg', upload_to=get_path) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) CoreUser.userprofile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) UserProfile.address = property(lambda u: Address.objects.get_or_create(useraddress=u)[0]) I think I must have made a big mistake in my lamda. UserProfile.address = property(lambda u: Address.objects.get_or_create(useraddress=u)[0]) my address model class Address(models.Model): street_number = models.FloatField(max_length=5, blank=True, null=True) street_line_1 = models.CharField(max_length=150, blank=True, null=True) street_line_2 = models.CharField(max_length=150, blank=True, … -
Sending canvas object with restfull api in django
I am using django as my backend and I am using restful api to communicate with react js frontend. I have created a pdf invoice with canvas and I was able to send it via mail system of django. But I also want to show the pdf on web page. So I need to send it to front end via api url. I tried to send it as response but I got the error: Object of type Canvas is not JSON serializable The code that I wrote to send pdf: return Response(c, status=status.HTTP_200_OK) c stands for the canvas object which is a pdf Is there a solution of this? Or how do I send the pdf to the front end. Thank you -
Can django channels communicate with Python web sockets instead of browsers? (Client is not html or javascript)
The server is configured as a channel on django. Will this server be able to connect to client.py implemented as Python's websockets Package or websocket-client Package? When I test it, there is an error as below. test python websocket-client source image error image -
How can I differentiate between two url requests from different HTML pages but with the same namespace in views.py?
I am creating a simple eBay like e-commerce website to get introduced with django. For removing an item from the watchlist, I placed two same links in two different HTML files, that is, I can either remove the item from the watchlist.html page or either from the item's page which was saved as listing.html. The url for both the pages look like this: <a href="{% url 'removeFromWatchlist' item.id %}"> Remove from watchlist </a> Now, in my views.py, I want to render different pages on the basis of the request. For example, if someone clicked Remove from watchlist from listing.html then the link should redirect again to listing.html and same goes for the watchlist.html. I tried using request.resolver_match.view_name but this gave me 'removeFromWatchlist' as the url namespace for both of these request is same. Is there any way I can render two different HTML pages based on the origin of the url request? Also, this is my second question here so apologies for incorrect or bad formatting.