Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Separate forms for all model instances
I wanna get next data from POST: [{'id': 1, 'number_of_product': 3, 'is_checked': on}, {'id': 2, 'number_of_product': 1, 'is_checked': off}], Now I have this: 'dishes': ['2', '2', '3', '4', '3', '2'], 'number_of_dish': ['2', '3', '1', '1', '1', '1'], 'checkbox': ['on', 'on'] class Dish(models.Model): """Dish model""" name = models.CharField(max_length=50, blank=False, null=False) category = models.ForeignKey( Category, on_delete=models.CASCADE ) price = models.DecimalField(max_digits=6, decimal_places=2, null=False) image = models.ImageField(upload_to='dishes/', blank=True, null=True) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) class OrderForm(forms.ModelForm): """Order creating form""" checkbox = forms.BooleanField(required=False) dishes = forms.ModelMultipleChoiceField(queryset=Dish.objects.all()) number_of_dish = forms.IntegerField( initial=1, min_value=1, label="Number: " ) class Meta: model = Order fields = ('date', 'dishes', 'number_of_dish') widgets = { 'date': DateInput( attrs={ 'class': 'form-control' }) } class HomeView(LoginRequiredMixin, CreateView): """Home view with order creating form""" template_name = 'pages/home.html' form_class = OrderForm success_url = reverse_lazy('pages:home') def post(self, request): # TODO: [{'id': 1, 'number_of_product': 3, 'is_checked': on}, {'id': 2, 'number_of_product': 1, 'is_checked': off}] print(request.POST) return HttpResponseRedirect(self.success_url) And my template page: <form action="" method="post"> {% csrf_token %} {% for dish in form.dishes %} {{ dish }} {{ form.number_of_dish | as_crispy_field }} {{ form.checkbox }} {% endfor %} <button type="submit" class="btn btn-primary">Order</button> </form> -
decoding to str: need a bytes-like object, HttpResponse found
While converting markdown to html i am getting this error def title(request, title): global mdValue mdValue = util.get_entry(title) htmlValue = m.convert(mdValue) # error occurs on this line return render(request, "encyclopedia/getpage.html", { "title" : htmlValue }) I have globally intialized m = Markdown() -
Django Channels doesn't release memory used by websocket after disconnect
Basically I have a django docker-container and I'm looking at memory usage through the docker stats. I'm using channels for websocket connections. When the first connection starts, memory usage goes from 60 to 65 mb. Throughout the connection memory slowly goes up. Then, when the connection stops it doesn't release any of the memory. I checked with del method and everything seems to be deleted. Any idea how I could check why the memory is not being released? Or what could be making the memory stay occupied? -
name 'MyAPI' is not defined while using Django rest_frameworkAPI
I am trying to deploy a ML model using Django rest framework, after setting up for approvals in the models.py for created project 'MyAPI' and setting up urls on both admin and of created project. And ran the bellow code. C:\Users\Padmini\DjangoAPI>python manage.py runserver got the following error File "C:\Users\Padmini\DjangoAPI\DjangoAPI\urls.py", line 21, in <module> path('api/', MyAPI.site.urls), NameError: name 'MyAPI' is not defined and my file arrangement as follows. there is DjangoAPI project folder and created app called 'MyAPI' -
i am trying to display certain items on a page, but i have a probelm with the if statement
I am trying to display items that have their warehouse field == to the warehouse name, so if the warehouse their are seeing has the same name as the warehouse field of the item they should see the items. I tried the following but it isn't working. {% for item in items %} {% if item.warehouse == warehouse.name %} <tr> <td>{{ item.pk }}</td> <td>{{ item.name }}</td> <td>{{ item.price }}</td> <td>{{ item.box_quantity }}</td> <td>{{ item.Quantity_in_box }}</td> <td>{{ item.code }}</td> <td>{{ item.category }}</td> <td>{{ item.supplier }}</td> <td>{{ item.expiry }}</td> <td> <a href="http://127.0.0.1:8000/admin/Inventory_Management/item/" class="btn btn-warning btn-sm" role="button"> Edit</a> <a href="http://127.0.0.1:8000/admin/Inventory_Management/item/" class="btn btn-danger btn-sm" role="button"> x</a> </td> </tr> {% endif %} {% endfor %} when i remove the if statement as follows {% for item in items %} <tr> <td>{{ item.pk }}</td> <td>{{ item.name }}</td> <td>{{ item.price }}</td> <td>{{ item.box_quantity }}</td> <td>{{ item.Quantity_in_box }}</td> <td>{{ item.code }}</td> <td>{{ item.category }}</td> <td>{{ item.supplier }}</td> <td>{{ item.expiry }}</td> <td> <a href="http://127.0.0.1:8000/admin/Inventory_Management/item/" class="btn btn-warning btn-sm" role="button"> Edit</a> <a href="http://127.0.0.1:8000/admin/Inventory_Management/item/" class="btn btn-danger btn-sm" role="button"> x</a> </td> </tr> {% endfor %} i get to see all the items. related view def Warehouse(request, pk): Warehouse = warehouse.objects.get(id=pk) items = item.objects.all() context = { 'items': items, 'warehouse': Warehouse, } return render(request, … -
How to run my view periodically till some end date?
I have a model for running the scrapy tasks. Now the view returns scrapped results after some time. There is no any use of two fields search_frequency and scraping_end_date for now. This fields will be used to run the scrapy view till the scraping_end_date at the given search_frequency value. For this problem How can I solve? Which approach will be better ? Is django only will be sufficient for this task? Any suggestions will be helpful. my model looks like this class Task(models.Model): task_status = ( (0, 'running'), (1, 'running'), (2, 'completed'), ) FREQUENCY = ( ('1', '1 hrs'), ('2', '2 hrs'), ('5', '5 hrs'), ('10', '10 hrs'), ('24', '24 hrs'), ) name = models.CharField(max_length=255) scraping_end_date = models.DateField(null=True, blank=True) status = models.IntegerField(choices=task_status) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) search_frequency = models.CharField(max_length=5, null=True, blank=True, choices=FREQUENCY) domain = models.URLField() -
Django AutoSlugField not considering soft deleted instances by Django Safe Delete
In our model we have a name and slug fields. This is how it looks like: class MyModel(CommonInfo, SafeDeleteModel): name = models.CharField(_('Name'), max_length=255, null=True, blank=True) slug = AutoSlugField(_('Url'), populate_from='name', unique=True,) For the slug field we generate an unique slug every time out model is saved. We are also using Django Safe Delete library to soft delete our model: Django Safe Delete Django Autoslug That means that for example if we create a new instance of our model with Name "My Model" it will auto generate a slug that will look like this: "/my-model". Now let's say we "soft delete" this instance with the slug "/my-model". In our database there will be a property deleted which contains the date when the model was deleted. We don't show this one in our application, it is completely ignored (because it is soft deleted, that's fine). The problem is that next time we create another one with the same name "My Model" it will auto generate the slug "/my-model" again, not considering that there is already one (which is soft deleted) with the same name and slug. We would need something like "/my-model-1" or whatever that is unique. We are missing the connection between … -
Is there a way to connect a wordpress website to a django web application?
I have two instances on AWS Lightsail, one for Wordpress and an other for Django. I have created a website using the CMS on wordpress and want to integrate the django application into that website. Is there any way to do this? There is a Django Wordpress API but i'm not sure if that would be helpful. Thank you in advance -
django shell xlrd.open_workbook() Errno 13
I have a set of data that I import from an excel spreadsheet. It is a requirement. It works fine on other PCs but on this one I get the error message: File "<console>", line 1, in <module> File "C:\Python38\lib\site-packages\xlrd\__init__.py", line 111, in open_workbook with open(filename, "rb") as f: PermissionError: [Errno 13] Permission denied: I am opening the file the usual way: import xlrd xl_workbook = xlrd.open_workbook('spreadsheet' + '.xlsx') I tried everything opening another file (no other excel file can be opened) reinstalling python (and pip installing the django and xlrd modules) restarting the PC I can assure the file is not open and from the python shell it works fine. But within the manage.py shell it fails. Can anyone help me? -
How to create new model/app/connector from the frontend using Django
I am not sure it could be done, but there is no harm asking i guess... :) So, I am trying to create a webapp in django which would manage user uploads - validate and normalize the data before a script could get it through the rest api for further processing (this script is not related to the webapp). It is fairly easy to create this webapp when there is only one type of dataset is expected to be submitted. But that is not the case unfortunately. So far I know how to create the model, forms, filters, validations etc. when there is only one dataset, but how could I let the users upload more then one type of datasets? (Not just 3 columns, but 6 for instance) In a perfect world it would work like this in my opinion: 1. An Admin-like user creates a new "connector" from the frontend: Let the user create a new "app"/"connector" from the frontend through a form where he/she could define how the models/forms/filters/validations should look like based on the fields the users want to submit (in the future) 2. The user can switch between connectors on the frontend: Let the user switch … -
Django Background Tasks Without command
I am new to Django and the django-background-tasks package. I am facing an issue that I couldn't do/start background task unless I forcefully run the command process_tasks , that is python manage.py process_tasks. I want to do/start background task without run the process_tasks command. i am creating rest api .So i want to run the background task automatically, with out writing the command. how it is possible. ? i found a code. thats is shown in below.. But i didt get in which file i put the code. from django.core.management import call_command call_command('process_tasks') this is my task.py @background(schedule=60) def rfid_sync(empid): try: print("Process start") emp = Employee.objects.get(EmployeeId=1) div = Device.objects.get(DeviceId=1) sync = Synchronization( Employee=emp, Device=div, SyncType=1 ) sync.save() except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) -
Password Reset , Django
I am trying to create a custom Password Reset Form in my website, but while using the Django's default templates it works fine, but when I create my own templates and override the existing templates on "urls.py" it strangely goes to "password_reset_confirm" from password_reset but in the Django repository on GitHub it is given as it should go to 'password_reset_done'. I am attaching the code and the images. path('reset_password/', auth_views.PasswordResetView.as_view(template_name = "registration/password_reset.html"), name = 'reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name = "registration/password_reset_sent.html"), name = 'password_reset_done'), path('reset/<uid64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name = "registration/password_reset_form.html"), name = 'password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name = "registration/password_reset_done.html"), name = 'password_reset_complete'), password_reset password_reset_complete -
django add-to cart as guest user
class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path,null=True, blank=True) featured = models.BooleanField(default=False) # quantity = models.IntegerField(default=1, null=True, blank=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) class OrderItem(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Cart(models.Model): user = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE) products = models.ManyToManyField(OrderItem, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) """i am trying to create a ecom website and trying to add products in cart without login the below code works with login user as request.user how to change it with guest user """ def add_cart(request, slug): item = get_object_or_404(Product,slug=slug) order_item ,created = OrderItem.objects.get_or_create( user=request.user, item =item, ) print(order_item) order_qs = Cart.objects.filter(user=request.user) if order_qs.exists(): order= order_qs[0] # check if the order item is in the order if order.products.filter(item__slug=item.slug).exists(): order_item.quantity+= 1 order_item.save() print("1") else: order.products.add(order_item) else: order = Cart.objects.create( user=request.user ) order.products.add(order_item) print("done") return redirect("cart:home") I am trying to create a ecom website and trying to add products in cart without the below code works with login user with request.user how to change it with guest user and perform add cart and and quandity … -
Django navbar link open in new tab
I am new to Django and I need some of the navbar items to open in a new tab. My problem is the target="_blank" does not work. I have checked that the if logic works. Here is the code in template <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> {% for navName, navUrl, openInNewTab in navItemsList %} {% if navItemsList == True %} <li class="nav-item active"> <a class="nav-link" href="{{ navUrl }}" target="_blank"> {{ navName }} <span class="sr-only">(current)</span></a> </li> {% else %} <li class="nav-item active"> <a class="nav-link" href="{{ navUrl }}"> {{ navName }} <span class="sr-only">(current)</span></a> </li> {% endif %} {% endfor %} </ul> </div> Here is the codes in view from django.http import HttpResponse from django.shortcuts import render from navbarItems.models import navItems def home_page(request): #Navigation items linkNames = [entry.linkName for entry in navItems.objects.all()] urls = [entry.url for entry in navItems.objects.all()] openInNewTab = [entry.openNewTab for entry in navItems.objects.all()] navigationItemList = list(zip(linkNames, urls, openInNewTab)) context = {"header_title" : 'Hidden Dimsum', "body_title" : 'Here is the title for the webpage', "navItemsList" : navigationItemList} return render(request, template_name = 'base.html', context = context) -
Code 324 Not Valid Video and Status failed?
I am trying to upload video through twitter API from my website. I scraped their github library code's async upload file for large files. I am uploading the data in chunks. This is the code: (Note I am using static file size and chunks for the testing purpose would definitely appreciate a dynamic method suggestion) MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json' POST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/update.json' CONSUMER_KEY = 'xxx' CONSUMER_SECRET = 'xxx' ACCESS_TOKEN = 'xxx-xxx' ACCESS_TOKEN_SECRET = 'xxx' VIDEO_FILENAME = request.FILES['video'] VIDEO_SIZE = 59467 oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET, resource_owner_key=ACCESS_TOKEN, resource_owner_secret=ACCESS_TOKEN_SECRET) request_data = { 'command': 'INIT', 'media_type': 'video/mp4', 'total_bytes': VIDEO_SIZE, 'media_category': 'tweet_video' } req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, auth=oauth) print req media_id = req.json()['media_id'] print('Media ID: %s' % str(media_id)) segment_id = 0 bytes_sent = 0 vid_file = VIDEO_FILENAME while bytes_sent < VIDEO_SIZE: chunk = vid_file.read(59467) print('APPEND') request_data = { 'command': 'APPEND', 'media_id': media_id, 'segment_index': segment_id } files = { 'media': chunk } req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, files=files, auth=oauth) if req.status_code < 200 or req.status_code > 299: print(req.status_code) print(req.text) segment_id = segment_id + 1 bytes_sent = vid_file.tell() print('%s of %s bytes uploaded' % (str(bytes_sent), str(VIDEO_SIZE))) print('Upload chunks complete.') request_data = { 'command': 'FINALIZE', 'media_id': media_id, 'media_category': 'tweet_video' } req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, auth=oauth) print(req.json()) processing_info = req.json().get('processing_info', None) … -
Django OAuth Toolkit + Django REST Framework = Response 401
I've use Django3.07, and i've setup Django OAuth Toolkit like was described in this tutorial documentation. Then i've installed Django Rest Framework like was described in the same tutorial. So my settings.py looks like this: ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'oauth2_provider', 'corsheaders', 'rest_framework', ] OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } AUTHENTICATION_BACKENDS = [ 'oauth2_provider.backends.OAuth2Backend', 'django.contrib.auth.backends.ModelBackend', ] MIDDLEWARE = [ 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] the urls.py looks like this: from django.contrib import admin from django.urls import path, include import oauth2_provider.views as oauth2_views from django.conf import settings from django.contrib.auth.models import User, Group from .views import ApiEndpoint, secret_page admin.autodiscover() from rest_framework import generics, permissions, serializers from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope # first we define the serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', "first_name", "last_name") class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ("name", ) # Create the API views class UserList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] queryset = User.objects.all() serializer_class = UserSerializer … -
How to use pyrebase query?
I'm learning how to use queries with python, django and pyrebase. I have a problem when querying multiple values of key. For example: This is my data structure: { "root": { "account": { "ACC0001": { "id": "ACC0001", "create_day": "2020-04-20 16:56:11", "create_by": "USE001", "brief_name": "AAAAA" }, "ACC0002": { "id": "ACC0002", "create_day": "2020-04-20 16:56:12", "create_by": "USE002", "brief_name": "BBBBB" }, "ACC0003": { "id": "ACC0003", "create_day": "2020-04-20 16:56:13", "create_by": "USE003", "brief_name": "CCCCC" }, "ACC0004": { "id": "ACC0004", "create_day": "2020-04-20 16:56:14", "create_by": "USE004", "brief_name": "DDDDD" }, "ACC0005": { "id": "ACC0005", "create_day": "2020-04-20 16:56:15", "create_by": "USE005", "brief_name": "EEEEE" }, ...... "ACC9999": { "id": "ACC9999", "create_day": "2020-04-20 16:56:15", "create_by": "USE100", "brief_name": "FFFFF" } } } } in SQL i use like "select * from AAA where I = 'USE002' and I = 'USE003' and I = 'USE004' and I = USE007" How can i do it in python, django and pyrebase get record of list user ? I just get exactly only one user. My code is below : config = { 'apiKey': "xxxxxx", 'authDomain': "xxxx.firebaseapp.com", 'databaseURL': "https://xxxx.firebaseio.com", 'projectId': "xxxx-92dec", 'storageBucket': "xxxx-92dec.appspot.com", 'messagingSenderId': "xxxx598699", 'appId': "1:xxxxx8699:web:xxxxx5a9e2920ec32e", 'measurementId': "xxxx360FN" } firebase = pyrebase.initialize_app(config) database = firebase.database() // how can get all record of lish create_by ['USE001','USE002','USE003'...] objuser = … -
How to return superscripted '2' (m2 or ft2) from django to template through render template?
Sorry for a dumb question but the below, def about(request): return render(request, 'blog_app/about.html', {'title': 'm<sup>2</sup>'}) shows this output in html, m<sup>2</sup> how to show like this, m2 -
Profile photo is not updated Django 3
My problem is the following, I am creating users with the default Django model, creating a user automatically creates a profile associated with this user, with the date of birth and profile photo fields. A profile photo is assigned by default, when I want to change it it is not updated, although the rest of the fields do, I have searched for solutions but none has helped me. Here the code: forms.py class ProfileForm(forms.ModelForm): birth_date = forms.DateField(label='Fecha de nacimiento') photo = forms.ImageField(label="Foto de perfil") class Meta: model = Profile fields = ['birth_date', 'photo'] views,py def editProfile(request): if request.method == 'POST': form = UEditF(request.POST, instance=request.user) extended_profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if form.is_valid() and extended_profile_form.is_valid(): form.save() extended_profile_form.save() return redirect('/') else: form = UEditF(instance=request.user) extended_profile_form = ProfileForm(instance=request.user.profile) context = { 'form': form, 'extended_profile_form':extended_profile_form } return render(request, 'registration/edit_profile.html', context) edit_profile.html {% extends "base_generic.html" %} {% block content %} {% load crispy_forms_tags %} <div class="container-fluid"> <div class="row justify-content-center"> <h1 style="padding-top: 0.5em; font-size: 4em; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;"> Editar el perfil del usuario {{ user.username }}</h1> <div class="container" > <div class="row justify-content-center"> <div class="col-6" style="background-color: #ffffff; padding: 2em; border-radius: 5%;"> <form method="POST" action="" novalidate> {% csrf_token %} {{ form|crispy}} {{ … -
Conditional Django migration based on a field only present in new version
My app that currently depends on Postgres and Django's Postgres-only JSONField. The field works well and I've no interest in another project, but I have prospective-users who want to use my app, but can't while it relies on Postgres. Django 3.1 has a cross-platform version of this field —which will work for my needs— but I don't want to force everybody up to Django 3.1; I would like to offer people a choice between Postgres or Django 3.1+. On paper, this is simple enough with a conditional import... try: from django.db.models import JSONField except ImportError: from django.contrib.postgres.fields import JSONField And if I installed Django 3.1 and generated a migration, it could take me from django.contrib.postgres.fields.JSONField to django.db.models.JSONField. But... New users will still execute the initial migration. I will still have a dependency on Postgres. Sub-Django 3.1 users won't be able to execute the new migration. I now have a dependency on Django 3.1. This is worse than when I started. How do I do this sort of field migration in a way that will work for everybody? -
The footer is not where it is supposed to be
I just faced a problem and I can't resolve it. I don't understand why the footer comes between the button of my calendar and the calendar itself. Callendar.html : {% extends 'base.html' %} {% block title %} Calendar {% endblock %} {% block content %} <div class="clearfix"> <a class="btn btn-info left" href="{% url 'cal:calendar' %}?{{ prev_month }}"> Previous Month </a> <a class="btn btn-info right" href="{% url 'cal:calendar' %}?{{ next_month }}"> Next Month </a> <a class="btn btn-info right" href="{% url 'cal:event_new' %}"> New Imputation </a> </div> {{calendar}} {% endblock %} base.html : <div class="wrapper"> {% include "header.html" %} {% include "menu.html" %} <div class="content-wrapper"> <section class="content-header"> {% block title_page %}{% endblock %} </section> <section class="content container-fluid"> {% block content %} {% endblock %} </section> </div> {% include "footer.html" %} </div> and the view of of my calendar : Views.py: @method_decorator(login_required(login_url='/userprofile/login/'), name='dispatch') class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context As the result actually i got this when i press F12 (inspect element) on the web page : <div class="clearfix"> <a class="btn btn-info left" … -
Forget password in Rest API
I am facing one issue in API.... I need to create a forget password API.... This is my views.py class ForgetPassword(PasswordResetView): def post(self, request, *args, **kwargs): -------------------- some codes ---------------------- send_email(email) data = {'status': 'success', 'message': 'send to your mail'} return Response(data, status=201) This code is working fine and I am getting an email .... But my issue is I am not getting this response in Postman .... It expect a token in header .... If I attach a login in header and pass this request it will give the exact response { "status": "success", "message": "send to your mail" } -
Does any one know how to customize shuup ? I want to add custom model,view and urls in shuup
I was trying to build a website using a shuup platform. But now , I want to add custom model,view, and URLs, Does anyone knows how to do it ?? -
I have been working on a django project , but I got stuck because of this error on sending email
socket.gaierror:[Errno -3] Temporary failure in name resolution -
Websocket Disconnected Connect Call Failed
I am following a turtorial Django Channel 2, I followed all steps and i am having a failed connection in console. I noticed this problem occur when i add Channel_layer to settings, when i remove Channel_layer the connection becomes successful. How do i solve this problem? Manager class ThreadManager(models.Manager): def by_user(self, user): qlookup = Q(first=user) | Q(second=user) qlookup2 = Q(first=user) & Q(second=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None qlookup1 = Q(first__username=username) & Q(second__username=other_username) qlookup2 = Q(first__username=other_username) & Q(second__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model( first=user, second=user2 ) obj.save() return obj, True return None, False Model.py class Thread(models.Model): first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first') second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() @property def room_group_name(self): return f'chat_{self.id}' def broadcast(self, msg=None): if msg is not None: broadcast_msg_to_chat(msg, group_name=self.room_group_name, user='admin') return True return False class ChatMessage(models.Model): thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='sender', on_delete=models.CASCADE) message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) Views.py class InboxView(LoginRequiredMixin, ListView): …