Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery revoke old task if new one is created with same arguments
I'm having trouble understanding the Celery queue and revokes. My main question is how to revoke (stop from executing) tasks that are already in the queue if a new task with the same name and arguments is created. so in pseudo-code new_task_to_be_added = some_task(1,2) if exists some_task in queue where some_task.args = (1,2): remove such task from queue new_task_to_be_added.add_to_queue() this is connected to password reset mechanism - User clicks 'create temporary password' and has 5 minutes to use this password to create a new - permanent - password. If the new password is not set in this time the account should be locked. But if after lets say 4 minutes user creates a new temporary password he should again have 5 minutes to change it but the "lock account" task will trigger in 1 minute - I want to stop that and always only use the newest task (with the same parameters) this is not a copy of: Revoke celery tasks with same args/kwargs this is actually reversed problem -
Save django variable using ajax
I'm trying to do a multistep form using Django 3. The context of this form it is to make a schedule for a exam. The user shall choose a day and time. But when day is chosen, a filter is applied to show the number of vacant seats. Here starts the problem. The way I've been planed to make this possible is using AJAX to collect a value from DATE option and send to back-end to filter. But, the value on back-end is not changing. Here is the code: model are: Day, Time and scheduling(day and time foreignkey) {% extends "base_restrictedArea.html" %} {% load filter_agenda %} {% block main%} <div class="container"> <div class="row"> <h2>Sscheduling</h2> <form id="multistep_form" action="{% url 'my_url' %}" method="post"> {% csrf_token %} <fieldset> {% for dates in date %} <input type="radio" id="model_date" value="{{ dates.id }}" name="model_date" onclick="myFunJs( '{{ datas.date|date:'d' }}' );">{{ datas.data }} {% endfor %} <input type="button" name="previous" class="previous action-button-previous" value="Previous"/> <input type="button" name="next" class="next action-button" value="Next"/> </fieldset> <!--time--> <fieldset> <table> <tr> <th>Time</th> <th>seats</th> <th>schedule</th> </tr> {% for times in time %} <tr> <td>{{ times.time}}</td> <td> vagass {% with result=scheduling|my_filter_day:varJsToDjango %} {{ result|my_filter_time:times.time }} {% endwith %} </td> <td><input type="radio" value="{{ times.id }}" name="model_time"></td> </tr> {% endfor … -
(Django) Code runs fine locally but seems to stop after second iteration in production
I am scraping a website for their data, using Selenium (Firefox). I've created a UI with some buttons, like "start scrape" and "stop scrape." When someone with access to the UI clicks either of these buttons, it makes a call to a Django Rest Framework API which starts or stops a scrape. Locally, everything runs fine and there seem to be no problems. However, in production, the scrape always only gets to the 2nd item that is to be collected. Here is the code: # api/views.py r = redis.Redis(host='localhost', port=6379, db=0, decode_responses='utf-8') @api_view(['POST']) @permission_classes((IsAuthenticated,)) @ensure_csrf_cookie def scrape_website(request): if request.method == 'POST': session_key = request.session.session_key r.set('scrape-stop-%s' % (session_key), 'no') r.expire('scrape-stop-%s' % (session_key), 60000) data = request.POST location = data.get('location') company_type = data.get('company_type') limit = data.get('limit') scrape(session_key, location, company_type) return Response({'msg': 'scrape successfully started'}) # scrape.py def scrape(session_key=None, location='united_states', agency_type='digital_marketing_agencies', limit=200): options = Options() options.headless = True profile = webdriver.FirefoxProfile() profile.set_preference("browser.download.dir", os.path.join(base_dir, 'reports')) profile.set_preference("browser.download.folderList", 2) profile.set_preference("browser.helperApps.alwaysAsk.force", False); profile.set_preference("browser.download.manager.showAlertOnComplete", False) profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference('browser.helperApps.neverAsk.saveToDisk','application/zip,application/octet-stream,application/x-zip-compressed,multipart/x-zip,application/x-rar-compressed, application/octet-stream,application/msword,application/vnd.ms-word.document.macroEnabled.12,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/rtf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/vnd.ms-word.document.macroEnabled.12,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/xls,application/msword,text/csv,application/vnd.ms-excel.sheet.binary.macroEnabled.12,text/plain,text/csv/xls/xlsb,application/csv,application/download,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/octet-stream') driver = webdriver.Firefox(firefox_profile=profile, options=options) print('Working...') driver.get(links[location][agency_type]) def get_boxes(location, agency_type, limit, index=0): print('index: %s' % (index)) boxes = driver.find_elements_by_xpath("//*[contains(@class, 'sc-AykKC') and contains(@class, 'sc-AykKD') and contains(@class,'hfxDgE')]") while index <= (len(boxes) - 1): box = boxes[index] index += 1 link_element = box.find_element_by_xpath(".//a[contains(@href,'profile')]") … -
How to install Django pg_trgm by makemigrations?
I have a Django app and a Postgresql database (in production). Now I want to intall pg_trgm extension for Postgres. But I can't find any step-by-step instructions for installing it from Django app. I have a superuser status. How to do it correctly? -
Python (Redis + DRF): Invalid input of type: 'NoneType'. Convert to a bytes, string, int or float first
I've got my redis running server, this is the configuration for it: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://TestPass1234@192.168.0.30:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } CACHE_TTL = 60 * 1 # 1 hour SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" This is my views.py: from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_cookie from rest_framework.viewsets import ModelViewSet from .serializers import TestSerializer from .models import Test # Create your views here. class NameofViewSet(ModelViewSet): serializer_class = TestSerializer queryset = Test.objects.all() #lookup_field = 'name_of_lookup_field' # and more.. @method_decorator(vary_on_cookie) @method_decorator(cache_page(60*60)) def dispatch(self, *args, **kwargs): return super(TestSerializer, self).dispatch(*args, **kwargs) And I have one object in the database, just to get something by requesting the URL. The error : [08/Dec/2020 02:17:25] "GET /tests/ HTTP/1.1" 500 158257 Internal Server Error: /tests/ Traceback (most recent call last): File "C:\Users\dziugas\.virtualenvs\test_cache-PBGnRHhx\lib\site-packages\redis\connection.py", line 643, in on_connect auth_response = self.read_response() File "C:\Users\dziugas\.virtualenvs\test_cache-PBGnRHhx\lib\site-packages\redis\connection.py", line 756, in read_response raise response redis.exceptions.AuthenticationWrongNumberOfArgsError: wrong number of arguments for 'auth' command During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\dziugas\.virtualenvs\test_cache-PBGnRHhx\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\dziugas\.virtualenvs\test_cache-PBGnRHhx\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
Reading the time zone of the end-user in Django
according to this apparently there is no way to read time zone of the end-user in Django. different methods all will read time zone of the server, rather than end user. I see that in javascript the following code will give time zone of the user and not server: const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; according to this which my test confirmed that. now my question is where would be the cleanest place to run the above code in a Django project which perhaps will be followed by an Ajax call to Activate() timezone. -
ValueError: invalid literal for int() with base 10: '' django
I created a models in django-framework but after run migrate, I got this type of error from django.db import models # Create your models here. class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) image = models.ImageField(upload_to="shop/images", default="") desc = models.CharField(max_length=300) pub_date = models.DateField() def __str__(self): return self.product_name but I get this error after run migrate PS C:\Users\Lenovo\Desktop\django-recap\django\myshopcart> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, shop Running migrations: Applying shop.0002_auto_20201208_0348...Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields_init_.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Lenovo\Desktop\django-recap\django\myshopcart\manage.py", line 22, in <module> main() File "C:\Users\Lenovo\Desktop\django-recap\django\myshopcart\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, … -
what is the best way to store and read data with python (django app)?
I am making a django website. I have some medium size data (around 50 Mo) that will be used for read only. They contain for example city names and codes and other inputs. I have tried several methods so far: store in json file and load with python or pandas store in csv file and read with python csv reader store it as a dict inside a variable, directly in a python module. like below: module.py my_dict_variable = {mydict} Json file is the slowest of all to read the data because of the loading time (I guess). CSV file is better but still quite slow. The last method is by far the fastest one (by a factor of minimum 10 compared to CSV). But I wonder if it's good practice or not. This data is used for query while typing request with Ajax, so I need to have really fast process and results. Do you guys have other ideas about the best/most efficient way to deal with such use cases? -
How to add django rest knox token django views
I would like to add jwt generated by django rest knox to authenticate users that login as well as verify users that sign up using an otp generator Here is the user profile model from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class UserProfileModel(models.Model): """The Model of the User Profile.""" account = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") profile_photo = models.ImageField() def __str__(self): return self.account.first_name Custom django user model class User(AbstractBaseUser, PermissionsMixin): mobile = models.CharField( _('mobile'), max_length=16, unique=True, help_text= _("Required. mobile number must be entered in the format: '+999999999'." ), validators=[validate_mobile], error_messages={ 'unique': _("A user with that mobile no already exists") }, ) email = models.EmailField( _('Email Address'), max_length=100, unique=True, help_text= _("Required. email number must be entered in the format: 'abc@abc.com'." ), validators=[validate_email], error_messages={'unique': _("A user with that email already exists.")}, ) password = models.CharField( _('Password'), max_length=128, help_text=_("Required. enter password."), ) first_name = models.CharField( _('first name'), max_length=30, blank=False, help_text=_('Required. Please enter name '), ) last_name = models.CharField(_('last name'), max_length=150, blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=False, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.'), … -
Using inline url() property with Django template {%staric 'img/header/header-1.jpg%}
I'm having trouble with displaying images with Django templates {%static%}. <div class="slide" style="background: url({% static "images/header/header-1.jpg" %}) center center; background-size: cover;"> However, I am successfully able to display an image with tag <img src={% static "images/logo.png" %} alt="Olga"> Thanks in advance -
Get Instagram followers count in Django
I'm building a dashboard for a client and I want to show their Instagram follower count. I've seen this done in many dashboards and I'm wondering how they do it. I have a working example that works in development but whenever I push it to production I get a huge string rather than the parsed number I usually get. def dashboard_view(request): def insta_follower_count(): user = "username" url = "https://instagram.com/" + user try: r = requests.get(url).text start = '"edge_followed_by":{"count":' end = '},"followed_by_viewer"' count = (r[r.find(start)+len(start):r.rfind(end)]) except: count = 'Could not fetch followers' return count context = { "insta_followers": insta_follower_count(), } return render(request=request, template_name='dashboard/dashboard.html', context=context) Perhaps there's a much better way of doing this? -
Finding all hardcoded string in big django project (Python 2.7)
I need to refactor a huge project written in django. I need a tool that can easily search all application code and find all of hardcoded strings, especially file paths. I have to move all these hardoces to settings.py. Is it possible to configure lint to only show hardcodes? Or maybe pycharm has tools/plugin for this? Thank You :) -
Django performance: Separate tables on database for each "user" for action model
class ActionModel(models.Model): target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, ) # django user that performed the action I have this action model. It has maybe 30 million records and counting. There is another follower model that count all actions for a given follower (target) for a specific user (AUTH_USER_MODEL) each time it query, and it also have 500K followers for most cases. So instead of having one huge 30M table - can I separate it to table per user ? so it will query faster, by only looking at a specific table ? I guess it like folders and files, better not put all images on same folder. right ? -
Django get best-selling product in a timeline
I have these models (with irrelevant fields removed) class VentaProducto(RegistroModel): unidad_inventario = models.ForeignKey('almacenes.UnidadInventario', on_delete=models.CASCADE, related_name='ventas') amount = models.DecimalField(max_digits=10, decimal_places=2) class UnidadInventario(RegistroModel): control_stock = models.ForeignKey('almacenes.ControlStock', on_delete=models.CASCADE, related_name='unidades_inventario') amount_producto = models.DecimalField(max_digits=10, decimal_places=4, default=Decimal('0.0000'), verbose_name='Amount of producto') class ControlStock(RegistroModel): producto = models.ForeignKey('productos.Producto', on_delete=models.CASCADE, related_name='stocks') class RegistroModel(models.Model): date_created = models.DateTimeField(auto_now_add=True, verbose_name='date created') And the Producto model, which is just basic information about the product. VentaProducto is the one where each sale is stored, name of product and how many were sold. The products currently in possession are in UnidadInventario, and ControlStock determines which product it is. I need to get a list of the (10,15, all) best-selling products in a day/month/year. How can I group each sale (VentaProducto) by product (VentaProducto.unidad_inventario.control_stock.producto), then adding their amount values to get the total amount sold, and display each product in a list? This is what I currently have, a list of each sale and this is what I want, a list of best-selling products in a day, done in paint I thought about adding an amount_sold filter to products, but I need to filter by date. I tried some things but I got stuck and realized it wouldn't work the way I want. How can I do … -
Send notifications to users in Django
I have a more general Django question on how to approach the following functionality. Think of the Facebook/Messenger; once you receive a like or message, you will instantly receive a red circle at the top with "1" (or just think of any other notification). I have a scenario where I wan't a user to get a notification if I for example add them to a certain group, preferably without having to reload the page. I have googled around and I think that WebSockets are the way to go, but it seems fairly complex and not many tutorials out there. Anyone has any feedback or if someone could point me in the right direction? If not in realtime and without having to refresh the page, I would somehow want the user to get a (1) notification in the navbar. Any thoughts/feedback appreciated! -
Object.Filter() error using boolean fields
When I try to use model.objects.filter(mybooleanfield=True) gives me this error ('42000', "[42000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server] A non-Boolean expression was specified in a context where a condition was expected, near 'mybooleanfield'. (4145) (SQLExecDirectW) ") But this only happens when use the filter with some BooleanField if I use PositiveIntegerField, CharField, DateTimeField or TextField there's no problem with the filter. I think this could be for the verions I use Python 3.9.0 Django 3.1.3 Pyodbc 4.0.30 Django-mssql-backend 2.8.1 I need to use as condition my BooleanField. Someone knows why this happend? -
Secured connection for Django app deployed with Docker
I've remote server with installed Ubuntu 20.04, Docker and Docker Compose. My Django app is deployed with Docker and running at http://my_server_ip_address:8000 How to make it use https instead of http??? Here is my Dockerfile content: FROM python:3 ENV PYTHONUNBUFFERED=1 RUN cd /usr/local/bin && python -m pip install --upgrade pip WORKDIR /code RUN ls . COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN ls . VOLUME /code And here is my docker-compose.yml file content: version: "3.8" services: db: restart: always image: postgres container_name: my_api_db environment: - POSTGRES_DB=my_api_db - POSTGRES_USER=my_api_db_user - POSTGRES_PASSWORD=my_api_db_password api: restart: always image: my_docker_image depends_on: - db container_name: my_api env_file: .env ports: - "8000:8000" command: bash -c " python manage.py makemigrations && python manage.py migrate && python manage.py create_super_user && python manage.py runserver 0.0.0.0:8000" Thank you in advance for any help! -
Django Dates and Times
I am trying to build a simple django eCommerce site. However, there are two issues I can't seem to solve(As of right now, I did not code anything up yet because I am brainstorming): Dates: How can I allow a user to select the dates for the items to be delivered or picked up? Also, I am wondering how I would take into account during leap years and possibly Daylight Saving? Example: If a user wanted to buy something, it should show the following days where users can pick which day the items to be delivered or picked up: (Today, Dec 7) , (Tomorrow, Dec 8) , (Wed, Dec 9) , (Thu, Dec 10) , (Fri, Dec 11) , (Sat, Dec 12), etc. . If the user decided to exit the page and came back to the page tomorrow, In addition, if the user decided to exit the page and came back to the page tomorrow, how can I show tomorrow's date and the future dates. Hours: How can I allow the business owner or third party seller set the hours for the items to be delivered or picked up? Preferably in like intervals? Example: Business owner/third party seller set … -
How to render ajax response by Django template language?
Render ajax response by Django template language I have template_name = "buzz.html" in class IndexView(TemplateView): Its get_context_data function defines json context and returns it. The content is rendered in the buzz.html using template language. The IndexView class also contains a function called def post(self, request, *args, **kwargs): The post function returns JsonResponse({"hi": "just testing"}) This post function gets called via ajax when I click a button on my html template. The success function in ajax defines the following: $("#res").html(json.hi); to show the content of hi in the div with id "res". The string "just testing" is displayed How can I get the post function to behave like the IndexView class so that I can use {{ hi }} template language instead of $("#res").html(json.hi)? -
Python Crash Course 19-1 project troubles
19-1. Blog: Start a new Django project called Blog. Create an app called blogs in the project and a model called BlogPost. The model should have fields like title, text, and date_added. Create a superuser for the project, and use the admin site to make a couple of short posts. Make a home page that shows all posts in chronological order. Create a form for making new posts and another for editing existing posts. Fill in your forms to make sure they work. I'm having issues trying to show the blog post title as well as the paired body of text underneath it. My current setup is showing the correct titles in order, but it's only showing the last entry for each bullet. models.py from django.db import models # Create your models here. class Blog_post(models.Model): """ Create new blog post """ title = models.CharField(max_length=60) date = models.DateTimeField(auto_now_add=True) body = models.TextField() def __str__(self): """ Return string representation of the title""" return self.title urls.py """ Define URL patterns for blog_app """ from django.urls import path from . import views app_name = 'blog_app' urlpatterns = [ # Home page path('', views.index, name='index'), ] views.py from django.shortcuts import render from .models import Blog_post # … -
How to make URL to the same location as a form in Django?
I have some Django app, which has a geolocation form, which I would like to understand how it works as an example. I can fill form with from and to addresses and when I press Go button it will open the following url http://mysite/?route_from=32.71568%2C-117.16171&route_to=34.05361%2C-118.2455&auto_update=false and it shows the route between cities. The form is encoded with {% block content %} {% with action=using_next|default:"home" %} <form method="get" action="{% url 'ui:'|add:action %}"> ... <input name="auto_update" type="hidden" value="false"/> <button type="submit">{% if using_next %}Go!{% else %}Save{% endif %}</button> </div> </div> </div> </form> {% endwith %} I was wishing to make static URL to instantly open the same route and added inside with <div class="row"> <div class="col-sm-10"> <div class="box"> <div id="predefined_01"> Example 01: <a href="{% url 'ui:'|add:action route_from='32.71568,-117.16171' route_to='34.05361,-118.2455' auto_update='false' %}">San Diego - Lon Angeles</a> </div> </div> </div> </div> I was thinking it will fill the same arguments as a form and navigate to the same place. Unfortunately, it swears upon render: NoReverseMatch at /settings/ Reverse for 'tracker' with keyword arguments '{'route_from': '32.71568,-117.16171', 'route_to': '34.05361,-118.2455', 'auto_update': 'false'}' not found. 1 pattern(s) tried: ['$'] settings is a current page. What I did wrong and how to fix? -
Timeout information in django q task
I'm running some functions with async_task() and I set the timeout. When the task exceeds the timeout I want to run the other function which tells the user about the failure. The problem is that I don't know how to get the information about stopping the task because of timeout. -
PisaDocument Not converting Image to Circular
I was making a pdf from html using xhtml2pdf.pisa in Django. But, after using a border-radius in image, the pdf shows image at rectangle. Here is my code:- def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() print(result.getvalue()) pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) return HttpResponse(result.getvalue(), content_type='application/pdf') In the html, #logo{ border-radius : 50%; width : 60px,; height : 60px; } {% if logo.url %} <img src="{{ logo.url }}" id="logo"> {% endif %} I checked and it is rendering properly in html, but not in the pdf. How can I make my images circular?? -
Error in Custom Implementation of Refreshing JWT Token
I used the simpleJWT in Django. The login works fine, however I want to implement a view for the refresh toke. So I get in the request body the access and refresh tokens, I check if the access token is still valid, and if its not then I generate a new one. However this implementation does not seem to work. (testing it with postman with given tokens it requests for the users details) serializers.py class RefreshSerializer(serializers.Serializer): accessToken = serializers.CharField(max_length=255, required=True) refreshToken = serializers.CharField(max_length=255, required=True) views.py class TokenRefreshView(APIView): permission_classes = () authentication_classes = () def post(self, request): received_json_data = request.data serializer = RefreshSerializer(data=received_json_data) if serializer.is_valid(): accessToken = received_json_data['accessToken'] refreshToken = received_json_data['refreshToken'] if (rest_framework_simplejwt.views.token_verify(accessToken).status_code != 200): user = rest_framework_simplejwt.authentication.JWTAuthentication.get_user(accessToken) refresh = RefreshToken.for_user(user) newaccesstoken = str(refresh.access_token) return JsonResponse({ 'accessToken': newaccesstoken }, status=200) else: return JsonResponse({ 'message': 'Token still valid', }, status=403) else: return JsonResponse({'message': serializer.errors}, status=400) -
Associating products with the Current Users in django
Currently If i try adding a new product , i get this error IntegrityError "Cannot assign "(<Merchant: aliyu>, False)": "Product.merchant" must be a "Merchant" instance" . what i want to achieve is product to be associated with the current user. class Product(models.Model): name = models.CharField(max_length=255, unique=True) date_added = models.DateTimeField(auto_now_add=True) merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE,null=True) class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) views.py def addproduct(request): if request.method=='POST': form=ProductForm(request.POST) if form.is_valid(): new_product=form.save(commit=False) new_product.merchant__user=request.user new_product.save() return HttpResponseRedirect('users:users_homepage') else: form=ProductForm() context={'form':form} return render(request,'users/addproduct.html',context) please help me.thanks beforehand.