Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
One to One Field throwing error "This field must be unique." django rest framework
I am stuck on this error when i send a post request to my django server it only seems to return "user": [ "This field must be unique." ] } and i have done a bit of debugging and found its related to the fact i am using a one to one field here is my: models.py from django.contrib.auth.models import User class EventPost(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) event_name = models.CharField(max_length=50 ) event_time = models.CharField(max_length = 50, default = '') event_date = models.CharField(max_length = 50, default = '') def __str__(self): return self.event_time serializers.py from rest_framework import serializers from .models import EventPost from django import forms from django.contrib.auth.validators import UnicodeUsernameValidator class EventPostSerializer(serializers.ModelSerializer): class Meta: model = EventPost fields = ( 'user', 'event_name', 'event_time', 'event_date', ) and my views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from .models import EventPost from .serializers import EventPostSerializer from rest_framework.permissions import IsAuthenticated # Create your views here. class PostViews(APIView): permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): data = { 'GET':'True', } return Response(data) def post(self, request,*args, **kwargs): serializer = EventPostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) I am quite new to django rest framework so please excuse me. Also … -
How can I auto run a python script in my django app deployed on heroku
I deployed my first Django app on Heroku, but I need to periodically execute the scraper I put in to update the data on the site. Right now I'm doing it manually, running the management command I created through the Heroku CLI. How can I set up an auto run for the scraper to start every hour? -
Creating Model for Django
After following this Tutorial https://docs.djangoproject.com/en/3.0/intro/tutorial02/ i encountered a problem. When i came to create my very first Model Django would refuse to do it. I have done it all. Django.setup() manage migrate make migrate and INSTALLED APPS. My init is empty and settings is vanilla as it gets except with the extra entry for installed app. This is my Project Structure. Picture data.py > from django.db import models > > > class bill_table(models.Model): > number = models.CharField(primary_key=True) > name = models.CharField() > adres = models.CharField() > status = models.CharField() > money = models.IntegerField() > > > class offer_table(models.Model): > number = models.CharField(primary_key=True) > name = models.CharField() > adres = models.CharField() > status = models.CharField() > money = models.IntegerField() settings.py > # Application definition INSTALLED_APPS = [ > 'django.contrib.admin', > 'django.contrib.auth', > 'django.contrib.contenttypes', > 'django.contrib.sessions', > 'django.contrib.messages', > 'django.contrib.staticfiles', > 'data', ] view.py > import data > > > def home(request): > return render(request, 'home.html', {'APP': render_to_string('dashboard.html')}) > > > def bill(request): > bills = data.bill_table.objects.all() > return render( > request, 'home.html', > {'APP': render_to_string( > 'app/bill.html', {'title': 'Offerte', > 'status': 'status', > 'rows': bills} > )}) i am done with this framework if it makes it so hard to do … -
Putting Break Points in Comments in Python (Django)
This is how my site is rendering - I tried putting <br> and </br> in a few places and I have not seen any impact. Does anyone have any ideas? <article class="media content-section"> <!-- comments --> <h3>{{ comments.count }} Comments</h3> <br><br/> {% for comment in comments %} <div class="media-body "> <a class="mr-2" href="#">{{ comment.name }}</a> <small class="text-muted">{{ comment.created_on|date:"F d, Y" }}</small> </div> <br><br/> <h2 class="article-title">{{ post.title }}</h2> <p class="article-content">{{ comment.body }}</p> <br><br/> {% endfor %} </article> -
Pass the data calculated by js to the database
I want to pass the values calculated by js to the database. I try to use ajax but it didn't work. could you give me some suggestions? <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> <script> window.onload= function score() { var value = sessionStorage.getItem("key"); var score = 0; if (value > 160) { score = 9; } else if (value < 161 && value > 140) { score = 8; } else if (value < 141 && value > 120) { score = 7; } else if (value < 121 && value > 100) { score = 6; } else if (value < 101 && value > 80) { score = 5; } else if (value < 81 && value > 60) { score = 4; } else if (value < 61 && value > 40) { score = 3; } else if (value < 41 && value > 20) { score = 2; } else if (value < 21 && value > 0) { score = 1; } else { score = 1; } document.getElementById("score").innerText = "Score: " + score; $.ajax({ url: "/score/", data: {score: score}, type: 'POST', }); } </script> I want to pass the score and view: if request.method == 'POST': score = … -
Couldn't find that process type (web) error on heroku
I'm trying to deploy a Django application to heroku, but i keep getting the following error when trying to scale my application: heroku ps:scale web=1 Error: Scaling dynos... ! ! Couldn't find that process type (web). I don't understand what am i doing wrong here, my file is called Procfile, it is located at the root of my project, here is how i defined it: Procfile web: gunicorn myproject.wsgi --log-file - -
Please help me to solve this issue
File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 260, in watched_files yield from iter_all_python_module_files() File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 105, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 141, in iter_modules_and_files resolved_path = path.resolve(strict=True).absolute() File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 1172, in resolve s = self._flavour.resolve(self, strict=strict) File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 200, in resolve return self._ext_to_normal(_getfinalpathname(s)) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' PS D:\pr\blog> -
object has no attribute 'title'
def __str__(self): """ String for representing the Model object """ return '%s (%s)' % (self.id,self.book.title) . class Book(models.Model): """ Model representing a book (but not a specific copy of a book). """ title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) # Foreign Key used because book can only have one author, but authors can have multiple books # Author as a string rather than object because it hasn't been declared yet in the file. summary = models.Text Field(max_length=1000, help_text="Enter a brief description of the book") is bn = models.Char Field('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.Many To Many Field('Genre', help_text="Select a genre for this book") # Many To Many Field used because genre can contain many books. Books can cover many genres. # Genre class has already been defined so we can specify the object above. def __str__(self): """ String for representing the Model object. """ return self.title i`m working on Django framework part Admin and when i want to enter part Book instances it shows this Error : 'None Type' object has no attribute 'title' , Can someone tell me why this happened? -
save() prohibited to prevent data loss due to unsaved related object on inherited object
I have following models structure: class Parent(models.Model): fieldA = models.TextField() fieldB = models.TextField() class Child(Parent): fieldC = models.CharField() I noticed some unexpected behavior in following code snippet: child = Child(fieldA = 'Text fieldA', fieldB = 'Text fieldB', fieldC = 'Text fieldC') child.full_clean() child.save() self.assertEqual(Child.objects.count(), 1) child.delete() self.assertEqual(Child.objects.count(), 0) child.full_clean() child.save() Not getting into why I add the second child.save(), assertions are passed, but when I want to save it with this second error it is failing with ValueError: ValueError: save() prohibited to prevent data loss due to unsaved related object 'parent_ptr' At the same time I don't see any such error with following code: parent = Parent(fieldA = 'Text fieldA', fieldB = 'Text fieldB') parent.full_clean() parent.save() self.assertEqual(Parent.objects.count(), 1) parent.delete() self.assertEqual(Parent.objects.count(), 0) parent.full_clean() parent.save() Why is that happening? Is someone able to tell me how I am supposed to fix the first snippet? -
Customize dashboard catalogue forms in Django Oscar doesn't work
I have followed the main documentations for django oscar. and i am trying to add a new field to product named video_url. first i add the new field to product models and it worked fine. catalogue/models.py from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): video_url = models.URLField(null=True, blank=True) from oscar.apps.catalogue.models import * and and then i continue to customize the catalogue dashboard but it seems like i didn't change any thing there's no error or anythin. dashboard/caralogue/forms.py from oscar.apps.dashboard.catalogue.forms import ProductForm as CoreProductForm class ProductForm(CoreProductForm): class Meta(CoreProductForm.Meta): fields = ['title', 'upc', 'description', 'is_public', 'is_discountable', 'structure', 'video_url'] myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'dashboard.catalogue', # Oscar 'django.contrib.sites', 'django.contrib.flatpages', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', # My Catalogue 'catalogue.apps.CatalogueConfig', # 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', # My Catalogue dashboard 'dashboard.catalogue.apps.CatalogueDashboardConfig', # 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', ] -
React SPA with initial state/route, served from Django
I am facing an unusual use-case with React and Django. My process starts with a POST request initiated by an app running on user's system to my Django server(The response is displayed on the browser). The POST request contains the data required for authenticating the user. Once authenticated, the server returns a simple HTML page customized for that user, including the details necessary to authenticate subsequent requests(like form submissions). Now I need to replace that simple HTML page with a react application. The problem is how can I embed the user specific info into the react app when returning the react app from server, so that I don't have to ask user to provide authentication information again once application loads on browser. Is this even possible while using react? -
Django DateTimeField query last hour
I'm trying to query the data from the last hour form a postgreSQL database, this is the table model in Django: class data(models.Model): fecha = models.TextField(db_column='Fecha', blank=True, null=True) # Field name made lowercase. hora = models.TextField(db_column='Hora', blank=True, null=True) # Field name made lowercase. lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) tipo = models.BigIntegerField(db_column='Tipo', blank=True, null=True) # Field name made lowercase. ka = models.FloatField(db_column='kA', blank=True, null=True) # Field name made lowercase. error = models.FloatField(blank=True, null=True) tiempo = models.DateTimeField(db_column='Tiempo',primary_key=True, blank=True, null=False) # Field name made lowercase. geom = models.PointField(blank=True, null=True) and this is what I have in my views file: from datetime import datetime, timedelta time = datetime.now() - timedelta(hours=1) def last_hour(request): hour = serialize('geojson',data.objects.filter(tiempo__lt=time)) return HttpResponse(hour, content_type='json') I haven been luckly with the information of other posts. My Django version is 3.0.5 and the timezone data in postgreSQL is utc-5 -
In Django REST Framework, how to filter list based on user?
I have two models, User and Book. Users own books and can only be seen by their owners. NOTE: the book model is handled in a separate database, so I can't use a foreign key on Book pointing to User. Not sure if this matters. If I'm authenticated, and send a GET /books request, I want only the books owned by the user to be shown. If I'm not authenticated, I should get a 403 error. Where should I implement this logic? I could do it in the View, with something like this: class BookView(APIView): """ Get books """ permission_classes = (IsAuthenticated, IsBookOwner,) queryset = Book.objects.all() serializer_class = BookSerializer def post(self, request): # create a book def get(self, request): books = Book.objects.filter(owner_id=request.user.owner_id) serializer = self.serializer_class(books, many=True) return Response(serializer.data) class IsBookOwner(permissions.BasePermission): """ Object-level permission to only allow seeing his own books """ def has_object_permission(self, request, view, obj): # obj here is a Book instance return obj.owner_id == request.user.owner_id Is this the correct way to do it? Also, is the IsBookOwner permission doing anything here? -
how can I run celery task only once in django?
from __future__ import absolute_import, unicode_literals from celery import shared_task from celery.task import periodic_task from celery.schedules import crontab from datetime import timedelta @periodic_task(run_every=(crontab(minute='*/1')), name='greeting_task') def greeting_task(): print('hello Dias!') Can I create a function that runs only once at certain time with crontab? PLEASE, HELP!!! thanks in advance! -
Hide a button when another is clicked with ajax
I'm currently triying to implement a voting system similar to the one in Hackernews. When the votearrow is clicked, the nuber of votes should update and the unvote button should appear. Since I don't want to reload the wholepage, I am using ajax to handle the votes requests. I'm struggling with the voting system (showing unvote and hiding votearrow when votearrow is clicked and vicecersa). With the current implementation when i clicked the votearrow, it hides as expected but does not show the unvote button (I need to reload) and the same happens with the unvote button, It hides but does not show the vote button... I have the following html template: ... {% for contribution in contribution_list %} ... {% if not user.is_authenticated %} <button onclick="location.href = 'http://127.0.0.1:8000/login/google-oauth2/?next=/';" id="myButton" class="votearrow"></button> {% elif contribution.id_contribution not in voted %} <button class="votearrow" id="vote{{ contribution.id_contribution }}" likehref='{{ contribution.get_api_like_url }}' userlike='{{ user.pk }}' contid='{{ contribution.id_contribution }}'></button> {% endif %} ... <span class="score">{{contribution.points.count}} point</span> by <a> {{contribution.author}} </a> <span class="age"> {{contribution.whenpublished}} </a> </span> {% if user.is_authenticated %} {% if contribution.id_contribution in voted %} <button class="unvote" id="unvote{{ contribution.id_contribution }}" likehref='{{ contribution.get_api_like_url }}' userlike='{{ user.pk }}' contid='{{ contribution.id_contribution }}'>Unvote</button> {% endif %} {% endif %} ... And … -
How do I view the first name of a user in Django?
I have set up my blog so that when a user clicks on the displayed name, it will go to that user's blogs (filtered that so only that person's blogs will show up). I used {{ view.kwargs.username }} to show the person's username, but I'd rather show the first name. What can I change to accomplish this? blog/templates/blog/user_post.html: {% extends 'blog/base.html' %} {% block content %} <h1 class="mb-3">Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded article-img mt-2" src="{{ post.author.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author.profile.user.first_name }} {{ post.author.profile.user.last_name }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% … -
Django - extract filtered data
I have a django-filter (OrderFilter) to display a filtered table, now I want to extract to excel the same filtered table. My code works but the get return blank. Can you help please ? Views.py def Order(request): filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date') """ Don't work Category_query = request.GET.get('Category') qs = Order.objects.filter(Category= Category_query) """ if request.GET.get('Export') == 'Export': response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xlsx"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows=qs.values_list('Date', 'Category', 'Item') for row, rowdata in enumerate(rows): row_num += 1 for col, val in enumerate(rowdata): if isinstance(val,datetime.date): val = val.strftime('%d/%m/%Y') ws.write(row_num, col, val, font_style) wb.save(response) return response return render(request, 'template.html',{'orders':orders,'filter': filter}) template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <form method="GET" > <button class="btn btn-warning" type="submit" value="Export" name="Export"> Export</button> </form> -
POST requests do not go through Google Cloud Endpoints? (Django REST)
My iOS app makes POST requests to Google Cloud Run container which hosts my Django Rest Framework Project. To add a layer of security I've set up public ESP (Extensible Service Proxy - Cloud Endpoints) to serve as a gateway for private Cloud Run Container. Basically, ESP does authentication before routing the request to private Cloud Run container. Django urls All GET requests to ESP work fine: they successfully get routed to Cloud Run Container (for example when I request non existent /hello at www.mysite.com/hello, I get Django Debug 404) However, for some reason, POST requests are not routed by ESP (for example I'm trying to access existing /upload at www.mysite.com/upload I get standard 404) I've tried disabling csrf, setting APPEND_SLASH to false, nothing seems to work. All POST requests result in 404. Am I doing something wrong in Django? All testing done with Postman. All POST requests work fine if sent directly to Cloud Run Container -
How to use a single model 'employee' for storing employees and managers in django?
I am creating a ERP type system, where I have a django model(table) called 'employee'. I want every worker of a company to be an 'employee'. (ex. coder, boss, janitor, line manager etc. will all be 'employee') I also want some employees to have one or more line manager/s. And a line manager can have multiple employee under him/her. So the question is how to make line manager a part of 'employee' table, and have a field which describes 'employees' under line manager? So that I can display what line manager/s an employee has. Also display what line manager has which employees under him? Here's the models file: class Team(models.Model): name = models.CharField(max_length=64) t_id = models.CharField(max_length=64) def __str__(self): return self.name class Employee(models.Model): first_name=models.CharField(max_length=64) last_name=models.CharField(max_length=64) e_id=models.CharField(max_length=64) current_role=models.CharField(max_length=64) # "coder" past_roles=models.CharField(max_length=512) # "coder, developer, janator" (seperator: ,) teams = models.ManyToManyField(Team, related_name="employees", blank=True) joining_date = models.DateTimeField(null=True,blank=True) desk_location=models.CharField(max_length=64) #How do I go about this? line_manager = ??? def __str__(self): return self.first_name I am new to django, so please forgive me if I am missing something very simple. Also if there is a more elegant solution which requires me to add additional tables, I dont mind. Thanks -
Confusion over Multiple Database Configuration
I am trying to use multiple database where one DB is a default and the second DB is a :memory DB. From the description in the Docs (shown below), it sounds like the default routing should be fine. But it says that the objects are "sticky" to their original database. How is there an "Original" database? When I first started to implement this, I expected that there would be a META in the Model classes that would specify its database, but that does not seem to be the case. I see examples where people have a Mapping of Apps to DB, which would be perfect for my scenario, but then they turn around and write a Routing anyway. I don't want to have to always add the database to Save calls, as this would be prone to programming errors. Is there an official setting to map an App to a Database, or a Model to a Database? Or is it always required to write a Router to use multiple databases. # Is DATABASE_APPS_MAPPING just a name that some developer chose to use or is it a # real Django thing that would do what I want? DATABASE_APPS_MAPPING = {'app1': 'default', … -
Wagtailstreamforms TypeError from_db_value() missing 1 required positional argument: 'context'
I got this error when trying to use wagtailstreamforms. Built a from-scratch environment and reproduced the error. The only things I installed: Django==3.0.5 wagtail==2.8 wagtailstreamforms==3.9 In base.py added (as prescribed in docs): 'wagtail.contrib.modeladmin', 'wagtailstreamforms' Left everything else untouched (standard Wagtail base.py), migrated database. Home page 127.0.0.1:8000 gives Wagtail's welcome page as expected, admin is at 127.0.0.1:8000/admin/ with Streamforms item in menu on the left as expected. When I click on it, I can make a form and when I make the first field for the form and then save it, I get the error above. After that I cannot access the Streamforms section anymore, I immediately get the same error when I try. I looked through all posts on SO on wagtailstreamforms and many similar items on the internet, no solution. What am I doing wrong? Complete error log: Internal Server Error: /admin/wagtailstreamforms/form/ Traceback (most recent call last): File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render … -
Django admin Tabularinline helptext
It seems like to that django admin allows the display of helptext for a model field, but I can't get it to display. I have an admin interface that looks like class ModelA(): name=DecimalField(blehbleh, help_text='some help plz') desc=DecimalField(blehbleh, help_text='some other help') class ModelAInlineAdmin(admin.TabularInline): model = ModelA formset = ModelAFormSet class ModelAFormSet(forms.BaseInlineFormSet): def clean(self): super(ModelAFormSet, self).clean() # some validation stuff class SomeOtherAdmin(admin.ModelAdmin): inlines = [ModelAInlineAdmin] model = some_other_model The ModelA's inline shows up in SomeOtherAdmin, but I cannot make the help text (i.e. 'some help plz' and 'some other help') to show. Any help? -
why my django id field get the value of user field?
Im new in django. I want to make a script that can make fake data with faker enter link description here this is my model.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional blood_type = models.CharField(max_length=2,blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) description = models.TextField(blank=True) case =models.CharField(max_length=30,blank=True) def __str__(self): return self.user.username this is my fake data function fake_first_name is variabale that has fake name that faker generated and so on for other variables def populate(N=5): for entery in range(N): #making fake data fake_first_name = fakergen.first_name() fake_last_name = fakergen.last_name() fake_email = fakergen.email() fake_password = fakergen.password(length=10) fake_blood_type = random.choice(bloodType) fake_phone = fakergen.phone_number() fake_case = random.choice(Case) Create new User entery user = User.objects.get_or_create( username=fake_first_name, first_name=fake_first_name, last_name=fake_last_name, email=fake_email)[0] tempUser = User.objects.get(username=fake_first_name) tempUser.set_password(fake_password) tempUser.save() userprofile = UserProfile.objects.get_or_create( user=fake_first_name, blood_type=fake_blood_type, phone_number=fake_phone, case=fake_case, description='')[0] and i get this error: ValueError: Field 'id' expected a number but got 'Lisa' -
Django OperationaL Error: No such column found
I was running a django project , that was working fine. Then just for testing, I deleted the migrations folder inside my app. After that I recreated the folder manually with __init__.py file. I was trying to add new columns in my models.py file. But after running python manage.py makemigrations python manage.py migrate I got the unknown column exception. I don't know add to retrieve my old migration folder. If not possible how to sync the new manually created migration folder so that I can change my existing model. I'm struck between the middle of project. Can anyone help me out? -
how can i update an Image field in Django: I want to let the user (employee) change his/her personal_image
Header 1 models.py: class Employee(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField(max_length=254) phone_number = models.PositiveIntegerField(default=None) address = models.CharField(max_length=200) position = models.CharField(max_length=200) hire_date = models.DateField(auto_now_add=False) salary = models.PositiveIntegerField(default=1000) is_manager = models.BooleanField(default=False) personal_image = models.ImageField(blank=True, null=True, upload_to='images/') password = models.CharField(max_length=200) def __str__(self): return str(self.pk) + " " + self.first_name + " " + self.last_name Header 2 forms.py: class change_image(ModelForm): class Meta: model = Employee fields = ['personal_image'] exclude = ('email', 'first_name', 'last_name', ' phone_number', 'address', 'position', 'hire_date', 'salary', 'is_manager', 'password') Header 3 views.py: if request.method == 'POST': form_4 = change_image(request.POST or None,request.FILES or None) if form_4.is_valid(): change_4 = form_4.cleaned_data emp = Employee.objects.filter(id=x.id) emp.update(personal_image=request.FILES['personal_image']) return redirect('/main') Header 4 settings.py: MEDIA_URL = '/images/'MEDIA_ROOT = os.path.join(BASE_DIR, 'employees/') Header 6 URLS.py: urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Header 7 HTML code: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group" style="width:500px;"> <label>Upload a new suitable profile picture showing at least your face.</label> {{form_4}} </div> <button type="submit" class="btn btn-primary">Upload</button> </form> what should I do to solve this issue, I'm able to change it but when I click on it from the database, it says that the image doesn't exist