Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Without assigning 'action' value in html tag of django project still it render the page and submit the value to database, How?
urls.py from django.contrib import admin from django.urls import path from poll import views urlpatterns = [ path('', views.poll_home, name="poll_home"), path('poll_details/<int:id>/', views.poll_details, name="poll_details"), path('<int:id>/', views.poll, name='poll') ] views.py def poll(request, id=None): if request.method == 'GET': try: question=Question.objects.get(id=id) except: raise Http404 return render(request, 'poll/poll.html',{'question':question}) if request.method == 'POST': user_id=1 data=request.POST['choice'] ret = Answer.objects.create(user_id=user_id,choice_id = data) if ret : return HttpResponse('Your vote is done successfully.') else: return HttpResponse('Your vote is not done successfully.') return render() poll.html {% extends 'employee/employee_home.html'%} {% block content%} <h1>Vote Page</h1> <h3>{{ question.title}}</h3> <form method="POST" action=""> {% csrf_token %} {% if question%} {% for choice in question.choices %} <input type="radio" name="choice" value="{{ choice.id }}"> <label>{{ choice.text }}</label> {% empty %} <p>There is no choice available for this question</p> {% endfor%} <button type="submit">Vote</button> {% else %} <p>There is no choice available for this question</p> {% endif%} </form> <h4><i>This question is created by {{question.created_by.first_name}}</i></h4> {% endblock content%} Even though I doesn't have mentions the action value in html page still it going to submit the data and successfully show the result I want to understand how django knows the action path -
please correct the errors below. django admin
I'm relatively new to Django and I'm currently leveraging the built in admin app. I am receiving the following error("please correct the errors below") whenever try to add/save an inline child group and whenever I do a simple edit to the Parent. If don't include the inline, adds, edits and deletes work fine. I'm not too sure how to resolve this. I've tried a few things based on what is available via google search, but still have not come to a resolution. here is a snippet of my model: class Group(models.Model): # Parent groupid = models.CharField('Group ID',db_column='groupId', primary_key=True, auto_created=True, default=uuid.uuid4, max_length=36) # Field name made lowercase. groupabbr = models.CharField('Group Abbr',db_column='groupAbbr', max_length=30) # Field name made lowercase. groupname = models.CharField('Group Name',db_column='groupName', max_length=100) # Field name made lowercase. groupemail = models.EmailField('Group Email',db_column='groupEmail', max_length=200, blank=True, null=True) # Field name made lowercase. # description = models.TextField(db_column='description', max_length=255, blank=True, null=True) description = models.CharField(db_column='description', max_length=255, blank=True, null=True) fkpripocpersonid = models.ForeignKey(Person,db_column='fkPriPocPersonId', related_name='priPocForGroups', on_delete=models.SET_NULL, max_length=36, blank=True, null=True, verbose_name='Primary POC') # Field name made lowercase. fksecpocpersonid = models.ForeignKey(Person,db_column='fkSecPocPersonId', related_name='secPocForGroups', on_delete=models.SET_NULL, max_length=36, blank=True, null=True, verbose_name='Secondary POC') # Field name made lowercase. primaryfieldtitle = models.CharField('Primary Field Title',db_column='primaryFieldTitle', max_length=100, blank=True, null=True) # Field name made lowercase. primaryfieldcontent = models.TextField('Primary Field Content',db_column='primaryFieldContent', blank=True, … -
Pass parameter to django form
I need to dynamically create a choice field in Django Form (not ModelForm) using the logged user as a parameter. The view: def cadastro(request): medico = request.user.medico usuario=request.user clinicas = medicos.clinicas.all() escolhas = tuple([(c.id, c.nome.clinica) for c in clinicas]) if request.method == 'POST': formulario = NovoProcesso(escolhas, request.POST) if formulario.is_valid(): formulario.save(usuario) else: formulario = NovoProcesso(escolhas) contexto = {'formulario': formulario, 'clinicas': clinicas} return render(request, 'processos/cadastro.html', contexto) Form class: class NovoProcesso(forms.Form): def __init__(self, escolhas, *args, **kwargs): super(NovoProcesso, self).__init__(escolhas, *args, **kwargs) self.fields['clinicas'].choices = escolhas clinicas = forms.ChoiceField(widget=forms.Select, choices=[]) # there are other fields here, but I ommited for the sake of clarity def(save): #custom save method.... I'm having trouble to understand the line: self.fields['clinicas'].choices = escolhas Not sure if I should write self.fields['clinicas].choices or . widget.... not sure how to write de form field inside the class. Tried several variations. I'm getting the following error: Internal Server Error: /processos/cadastro/ Traceback (most recent call last): File "/home/lucas/dev/.virtualenvs/autocusto/lib/python3.8/site-packages/django/forms/forms.py", line 158, in getitem field = self.fields[name] KeyError: 'errors' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/lucas/dev/.virtualenvs/autocusto/lib/python3.8/site-packages/django/template/base.py", line 828, in _resolve_lookup current = current[bit] File "/home/lucas/dev/.virtualenvs/autocusto/lib/python3.8/site-packages/django/forms/forms.py", line 160, in getitem raise KeyError( KeyError: "Key 'errors' not found in 'NovoProcesso'. Choices … -
Django - How to share data between ASGI and WSGI applications?
I make my project on Django, it has Gunicorn on WSGI, Daphne on ASGI. ASGI server needed only for handling Websocket protocol. Using Channels in Django for Websocket routing and handling. Nginx on static and proxy. Database is Mysql. Generally: is there a way to synchronise variable values in memory between ASGI and WSGI app without writing to database? TLDR: HTTP (wsgi) works for major interacting with database (for now, creating instances of models). Websocket (asgi) is planned to work with user controls (for now, connect to rooms, in future, would be in-game controls? rotate piece etc. The project is Tetris multiplayer, where users can create rooms, for example, for 2 or 4 players (parallel tetris fields), when created other players can connect into that rooms.) 'Under the hood' there is 'engine' (some data is stored in memory when the server runs): # engine/status.py active_rooms = {} when creating a new room, HTTP controller (from views.py) calls function: import engine.status as status from engine.Room import Room def create_room(id, size): new_room = Room(size) ... status.active_rooms[id] = new_room ... So, it writes a new key-value pair into dict (status.active_rooms), whers key is number(id), value is instance of class 'Room'. When other player … -
how send Firebase Notification in Django admin on save_model
Notification are already working in the view class. But not working in admin.py I do send the puh notification after the save record in save_model. but not working here is my method class EventAdmin(admin.ModelAdmin): list_display = ('event_name', 'event_type', 'event_city', 'event_organizer', 'start_date', 'start_time', 'end_date', 'end_time', 'is_approved', 'is_active', 'created_at') fields = ('main_image', 'event_name', 'event_organizer', 'event_type', 'event_city', 'event_tag', 'event_address', 'event_description', 'event_notes', 'start_date', 'start_time', 'end_date', 'end_time', 'age_max', 'age_min', 'event_lat', 'event_lng', 'website', 'is_approved', 'is_active', 'created_at') def save_model(self, request, instance, form, change): user = request.user instance = form.save(commit=False) if not change or not instance.created_by: instance.created_by = user # Here is notification class notifiClass = Notifications() notifiClass.sendNotifications(instance) else: instance.is_updated = True instance.modified_by = user instance.save() form.save_m2m() return instance here is my Notification class in admin.py class Notifications(object): def sendNotifications(self, data): users = models.NewEventNotification.objects.all().filter(is_notify=1) serializer = NewEventNotificationSerializer(users, many=True) tokens = [] for user in serializer.data: tokens.append(user['user_token']) if tokens: push_service = FCMNotification(api_key=api_key) message_title = "New Event" message_body = data result = push_service.notify_multiple_devices( registration_ids=tokens, message_title=message_title, message_body=message_body) print(result) this shows the result in browser TypeError at /admin/events/event/add/ Object of type Event is not JSON serializable Request Method: POST Request URL: http://192.168.0.104:8000/admin/events/event/add/ Django Version: 2.1.5 Exception Type: TypeError Exception Value: Object of type Event is not JSON serializable Exception Location: C:\Python\Python37-32\lib\json\encoder.py in … -
How does Django handle JOIN like filter statements?
I have some code that consists of 3 models, namely Course, Section and Lecture. A Course has many sections, a Section has many Lectures. Say i want to retrieve all the Lectures that belong to a particular Course, Course also has a property called 'title' so thats what will be used to filter. According to the tutorial i'm reading i should do this to get the lectures: Lecture.objects.filter(section__course__title = "title of course) This is pretty straightforward but what i'm wondering is how django is handling this under the hood. Some joins must be involved i can imagine, but according to the answer of this thread Does Django support JOIN? Django cannot make Joins. But when i look at the links he provides i can read that django does handle joins behind the scenes. So lets assume django does handle joins, how does it know when to make a left join or a regular join? A regular join can only be made when it is certain that every parent model has a reference to a child model, the field is marked not null. If it can be null then a left join should be used. Is django intelligent enough to know … -
how to use Django pagination with hidden search parameters
I am using Django for the backend (version 1.11.4) and python 3.6. I have a search form which has many searching parameters. I used POST method to submit the form. Everything is working fine. However, I made pagination using Django pagination. When I click on the next (through anchor tag). I got some error. Let me elaborate more here. I used post method to hide search parameters from users. However, I pass the page number through anchor tag which includes page number and the variable “path” caught up on the view function. This method working fine but it shows all searching parameters as well as the token when I click on the next link. When I passed the page number only, I got an error asking for the “result list” which is a variable inside of view function has the search result. The search result is inside the “if request.method==“POST”:" That is why it is undefined. Now what obvious to me from what I know. I have 3 methods to do the pagination using Django as follow: 1- I continue the same method. Catch up the path in the url as follow: path += "%s" % "&".join(["%s=%s" % (key, value) … -
how to build fourm in django?
Currently users are allowed to use Javascript in bbPress posts. I would like to disable this for security reasons but cannot find the "off" switch. I have looked for plugins, settings and other questions to no avail. -
i have 600 records in my postgres database, now when i inserted from django it's generating primary duplication error
I have inserted data into table from postgresql directly. Now when I try to insert data from django application, it's generating primary key duplication error. How can I resolve this issue? -
How do you filter django-oscar products to show only products from a specific category?
I'm quite new to django-oscar and i'm trying to figure out how i can create a queryset that only returns products with a certain category on a section in my template, for instance all products with the category 'electronics'.How can i go about this? -
Media Files not shown in DEBUG=False Django 2.2.6
Every thing works perfect in debugging mode but can't show the media files on production environment while debugging id false That's my settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.csrf', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.static', 'django.template.context_processors.media', ], }, }, ] TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", "django.core.context_processors.debug", "django.core.context_processors.auth", "django.core.context_processors.i18n", "django.core.context_processors.media", ) STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,] STATIC_ROOT = os.path.join(BASE_DIR, 'staticroot') # Media folder for database media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and the project urls if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, serve, document_root=settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, serve, document_root=settings.MEDIA_ROOT ) Although the url link path shows perfectly using template tags {% load staticfiles %} <a href="{{ magazine.document.url }}" target="_blank"> <i class='far fa-file-pdf'></i> </a> Hope you can help to fix this issue. -
Django - URL template tag with 2 arguments
I'm new to Django and sorry if the question is silly. I have a URL with two slugs, one for the category which is a manytomany field and one for the posts: path('<slug:slug_staticpage>/<slug:slug>/', views.post, name='post_detail') views.py def post(request, slug, slug_staticpage): category = get_object_or_404(StaticPage, slug_staticpage=slug_staticpage) blogpost = get_object_or_404(Post, slug=slug) post = Post.objects.filter(slug=slug) page_id = category.pk related_posts = Post.objects.filter(static_page__pk=page_id)[:6] return render(request, "blog/blog-post-final.html", {'slug': slug, 'slug_staticpage': category.slug_staticpage, 'post':post, 'related_posts':related_posts}) models.py class Post(models.Model): title = models.CharField(max_length=300) content = RichTextField() slug = models.SlugField(max_length=200, unique=True) published = models.DateTimeField(verbose_name="Published", default=now()) image = models.ImageField(verbose_name="Image", upload_to="blog", null=True, blank=True) author = models.ForeignKey(User, verbose_name="Author", on_delete=models.PROTECT) categories = models.ManyToManyField(Category, verbose_name="Categories", related_name="get_post") static_page = models.ManyToManyField(StaticPage, verbose_name="Página estática", related_name="get_post") created = models.DateField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=STATUS, default=0) I want to display those URLs in my homepage via the template tag, but I don't know how to retrieve the slug_staticpage slug: <a href="{% url 'blog:post_detail' slug_staticpage=post.slug_staticpage slug=post.slug %}"> The above syntax is not working, I can only retrieve the slug of the post. Can someone help me sort this out? Thanks a lot for your precious help :) Askew -
Hosting Jupyter Notebook Python App on a Webpage
I've made a simple python GUI application using ipywidgets, ipycanvas, and numpy. I made the program on Jupyter notebook as an ipynb file. I would now like to take my application and put it on a webpage. What is the best way to take this Jupyter notebook app and host it on the web? I've looked a bit into Binder and Django, but I can't seem to find enough resources or documentation on the net to help me learn how to do this. -
Django Rest Framework ListSerializer Partial Update
I'm writing a serializer to provide multiple partial updates to a django model. I'm following the example implementation that appears in the DRF api guide, reproduced below and linked here: https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update. The following was retrieved from django-rest-framework documentation: serializer.py class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping: book.delete() return ret class BookSerializer(serializers.Serializer): # We need to identify elements in the list using their primary key, # so use a writable field here, rather than the default which would be read-only. id = serializers.IntegerField() ... class Meta: list_serializer_class = BookListSerializer In my code I'm getting a NotImplementedError('update() must be implemented.') in my views.py when .save() is called on the serializer that is returned. My understanding is that the ListsSerializer overrides the .update(), so could anyone help explain why I'm getting the NotImpletmentedError? views.py elif request.method == 'PATCH': data = JSONParser().parse(request) books = … -
Django - How can i get this objects count based on this relationship
I have two models which are Influencer and InfluencerList. My model relationships are: User and InfluencerList have many-to-one relationship (one user can have many lists) Influencer and InfluencerList have many-to-many relationship (one influencer can be in multiple lists or one list can contain multiple influencers) I want to display logged in users each lists name and count (how many influencers are in it) I managed to list users own lists but i couldn't figured out how to get counts of that list. I suppose it should be done by using lookup (association) table. Here is my model.py: class Influencer(models.Model): # fields are not included for clarity def __str__(self): return self.url class InfluencerList(models.Model): name = models.CharField('Name:', max_length=20, blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') influencers = models.ManyToManyField('Influencer', related_name='lists') def __str__(self): return self.name # some method like getCount() would be nice here view.py: class InfluencerListView(LoginRequiredMixin, ListView): model = Influencer context_object_name = 'Influencers' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) logged_in_user = self.request.user context['InfluencerLists'] = logged_in_user.lists.all(); return context I'm also not sure if i have to add a field like count to my InfluencerList model. It would be very nice if someone could explain why or why not i should do that. Thank you for … -
Django Rest Framework Serializers: read_only parameter has no effect
Read Only settings doesn't work properly. No matter if I use read_only_fields: read_only_fields = ('id', 'user', 'created_at', 'account_type', 'balance', 'iban') or read_only for each serializer field: class BankAccountSerializer(serializers.ModelSerializer): id = serializers.StringRelatedField(read_only=True) user = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField(read_only=True) account_name = serializers.StringRelatedField(read_only=False) account_type = serializers.StringRelatedField(read_only=True) balance = serializers.StringRelatedField(read_only=True) iban = serializers.StringRelatedField(read_only=True) class Meta: model = BankAccount fields = '__all__' def get_created_at(self, instance): return instance.created_at.strftime("%B %d %Y") This is what my database model looks like: class BankAccount(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='bankaccounts') created_at = models.DateTimeField(auto_now_add=True) account_name = models.CharField(max_length=255) account_type = models.CharField(max_length=10, choices=POSITIONS) balance = models.DecimalField(decimal_places=2, max_digits=12) iban = models.CharField(max_length=22) def __str__(self): return str(self.iban) My permission classes are the following ones: permission_classes = [IsUserOrReadOnly, IsAuthenticated] Whereby the custom IsUserOrReadOnly class looks like this: class IsUserOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.user == request.user My serializer/view looks like this: class BankAccountViewSet(viewsets.ModelViewSet): queryset = BankAccount.objects.all() lookup_field = "iban" serializer_class = BankAccountSerializer permission_class = [IsUserOrReadOnly, IsAuthenticated] What I get from the api endpoint (options method response) is not the result I am expecting, means the field account_name is still "read_only": true, as can be seen in the browsable api output: "actions": { "PUT": { "id": { "type": … -
Update model field names before saving
I'm using django import_export module to import excel files. Some column names of the excel files are two or more words, which makes it difficult to use them as field names for a django model. Is there a way to replace the spaces with underscores, for example Column 1 with Column_1 before saving? Thank you for any suggestions. -
Django-Admin On extending change_list page, the styling(css/bootstrap) of the admin page becomes non functional
I simply extended the default change_list.html in order to open a modal on a custom button click. But the default styling of the admin page is not working, seems like it is getting overridden due to import of css and bootstrap in my modal.html. What can be done to achieve the default styling of the django admin page? Below is the code- modal.html {% extends "admin/change_list.html" %} {% block result_list %} <style> .modal-body { max-height: 150px; overflow-y: scroll; } </style> <!-- Modal --> <div class="modal fade" id="bsModal3" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="mySmallModalLabel">Script+Html</h4> </div> <div class="modal-body"> <pre id="script-html-response"></pre> </div> </br> <div class="modal-header"> <h4 class="modal-title" id="mySmallModalLabel1">Script</h4> </div> <div class="modal-body"> <pre id="script-response"></pre> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> {{ block.super }} {% load staticfiles %} <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script type="text/javascript" src="{% static 'admin/js/view_widget_script.js' %}"></script> {% endblock %} -
How can I calculate avg of data from django form and store in variable for later use?
In the readerpage function, in my views.py, I am trying to calculate the avg of the two variables: readability_rating and actionability_rating, and store the result in avg_rating def readerpage(request, content_id): content = get_object_or_404(Content, pk=content_id) form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.content = content readability = form.cleaned_data['readability'] readability_rating = forms.ChoiceField( choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]) actionability = form.cleaned_data['actionability'] actionability_rating = forms.ChoiceField( choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]) general_comments = form.cleaned_data['general_comments'] avg_rating = (float(readability_rating) + float(actionability_rating)) / 2 review.save() return redirect('home') args = {'content': content, 'form': form} return render(request, 'content/readerpage.html', args) The problem is that with this setup the two variables are still ChoiceFields - as such the above setup gives me the error: float() argument must be a string or a number, not 'ChoiceField' I’ve tried converting them to floats without any luck. I also attempted using the TypedChoiceField with coerce=float, still with no luck I’m not sure whether the best place to calculate this is in my function, my form, or my model? models.py: class Review(models.Model): content = models.ForeignKey(Content, null=True, on_delete=models.CASCADE) readability = models.CharField(null=True, max_length=500) readability_rating = models.IntegerField(null=True) actionability = models.CharField(null=True, max_length=500) actionability_rating = models.IntegerField(null=True) general_comments = models.CharField(null=True, max_length=500) … -
Compare Django child classes of abstract model in Django
I have two classes as childs of abstract class (example below). How to check if queryset model is one or other of these classes? class Parent(models.Model) field_a = models.CharField(primary_key = True, max_length = 24) field_b = models.CharField(primary_key = True, max_length = 24) class Meta: abstract = True class A(Parent) pass class B(Parent) pass I have tired something like this but it's not working: if type(queryset.model) == type(A): do something... elif type(queryset.model) == type(B): do something else... because when I check the type(queryset.model) it's returns type(Parent), even the queryset.model is the A or B class. -
How to add to cart in DRF
I am trying to create order: models.py: class OrderItem(models.Model): image_number = models.CharField(max_length=20) title = models.CharField(max_length=20) image_size = models.CharField(max_length=50) file_type = models.CharField(max_length=20) price = models.CharField(max_length=50) def __str__(self): return self.title class Order(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return str(self.user) serializers.py: class AddtocartSerializers(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['image_number','title','image_size','file_type','price'] class CartSerializers(serializers.ModelSerializer): class Meta: model = Order fields = ['item', 'start_date', 'ordered_date' ] views.py: class AddtocartView(viewsets.ModelViewSet): authentication_classes = [] permission_classes = [] pagination_class = None queryset=OrderItem serializer_class = AddtocartSerializers class CartView(viewsets.ModelViewSet): authentication_classes = [] permission_classes = [] pagination_class = None queryset=Order.objects.all() serializer_class = CartSerializers urls.py: api endpint path('addtocart/',views.AddtocartView.as_view({'get':'list'}),name='addtocart'), path('cart/',views.CartView.as_view({'get':'list'}),name='cart'), I am confused here; should I create new order objects from serialzers or views? -
Get data with base url by values()
I have a image table that have more than 10k images. models.py class Image(models.Model): image = models.ImageField(upload_to='image') tag = models.CharField(max_length=100) views.py Image.objects.filter(tag__icontains=tag).values('image') By above query i am getting data in this format. [ { "image": "image/mcml4__9_ipmVd6E.jpeg", }, { "image": "image/mcml4__df9_ipmfgdfVd6E.jpeg", } ] but i need this with base url. [ { "image": "http://{{baseurl}}/media/image/mcml4__9_ipmVd6E.jpeg", }, { "image": "http://{{baseurl}}/media/image/mcml4__9_ipmVd6E.jpeg", } ] How can i do this with orm query only without manipulation in python memory. -
Django: TimeoutError: [WinError 10060] A connection attempt -> mail backends not correctly set?
I currently develop a Django project and want to send email for 2 purposes: password reset database update I have a registration app I developp following https://simpleisbetterthancomplex.com tutorials and it works well. For tutorial purpose, reset send email in console. I would like to test real email sent using my google account (even if it will probably not be the service I will use but I want to understand concepts) I have read the Django doc about email sending I have the Django default authentification and a function email() for database update called in code when one of my models is updated At home it works but in my entreprise, I got the following error: TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond it is a firewall problem I guess... I should I resole it? models.py def email(patient,strategie,medicament): subject = 'Patient ' + patient + ' randomisé ' message = 'Le patient ' + patient + ' a été randomisé dans la stratégie ' + strategie + ' et a reçu le numéro de boite ' + … -
Django Rest Framework - is it possible to add sorting to pagination
I have following code class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 class ListAllPrePayedV2(generics.ListAPIView): serializer_class = PrePayedSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): queryset = PrePayed.objects # lcode lcode = self.request.query_params.get('lcode', None) if lcode is not None: queryset = queryset.filter(lcode=lcode) # lcode payed_by = self.request.query_params.get('payed_by', None) if payed_by is not None: queryset = queryset.filter(payed_by__icontains=payed_by) # order_by_date order_by_date = self.request.query_params.get('order_by_date', None) if order_by_date is not None: queryset = queryset.order_by('date') # order_by_payed_at order_by_payed_at = self.request.query_params.get('order_by_payed_at', None) if order_by_payed_at is not None: queryset = queryset.order_by('payed_at') if order_by_payed_at is None and order_by_date is None: queryset = queryset.order_by('pk') return queryset the problem is that sorting never works. is it possible in such set-up or I do something wrong ? if not possible in this, how can I do it ? -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
I'm trying populate data in my modal using Faker but I got the error. here is my Code import os from faker import Faker from first_app.models import Topic, Webpage, AccessRecord os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myfirst.settings') import django django.setup() import random fakegen = Faker() topics = ['search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top=add_topic() fake_url=fakegen.url() fake_date=fakegen.date() fake_name=fakegen.company() webpg=Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] acc_rec=AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__=='__main__': print('populating script') populate(30) print('Completed') I think error is due to this line os.environ.setdefault but when I comment this line it doesn't populate data Below is the error django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJA NGO_SETTINGS_MODULE or call settings.configure() before accessing settings.