Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to insert excel file into sql satabase of django and then read that file?
What i want to do is that i want to save an excel file into my db. I am working on python django and db is sql. Currently i have given path of my file to a variable and then reading that file. But i want to save file in database through choose file tag in html. Kindly help me in this regard -
I want to remove new line if present in a string using html django (python)
urls: path('admin/', admin.site.urls), path('',views.index,name='index'), path('analyze',views.analyze,name='analyze'), index.html <form action='/analyze' method='get'> <textarea name='text' style='margin: 0px; width: 721px; height: 93px;'></textarea><br> <input type="checkbox" name="removepunc"> Remove Punctions <br> <input type="checkbox" name="fullcaps"> Uppercaps<br> <input type="checkbox" name="newlineremove"> New line remove<br> <button type="submit">Analyse text</button> analyze.html: <body> <h1>Your analyzed text</h1> <p> <pre>{{analyzed_text}}</pre> </p> views.py: def index(request): return render(request,'index.html') def analyze(request): djtext=request.GET.get('text','default') newlineremove=request.GET.get('newlineremove','off') print(newlineremove) print(djtext) if newlineremove == "on": analyzed="" for char in djtext: if char !="\n": analyzed=analyzed + char else: analyzed=analyzed + " " print(analyzed) params={'analyzed_text':analyzed} return render(request,'analyze.html',params) suppose newlineremove=="on" and input is: dam dam output is(for print in terminal): on dam dam dam but it was supposed to be: on dam dam dam dam but on the web (analyze.html) dam dam -
How to search a queryset by id without additional db calls in Django
Is there a way to search a Django queryset by id or a combination of fields without making additional calls to the database. Would something like this be a single db query? qs = Employee.objects.filter(restaurant='McDonalds') emp1 = qs.filter(id=1) emp2 = qs.filter(id=2) emp3 = qs.filter(id=3) Or is the only way to do something like this to map ids to the model instances beforehand? qs = Employee.objects.filter(restaurant='McDonalds') emp_map = {instance.id: instance for instance in qs} emp1 = emp_map.get(1) emp2 = emp_map.get(2) emp3 = emp_map.get(3) -
Django doesnt registrate my models from addon
I have migrated from Django 1.8 to 2.2 and I cant solve problem with database for few days. I have addon registrated in INSTALLED_APPS, then I have folder of my addon with apps.py,models.py and logic.py. Registration in INSTALLED_APPS: INSTALLED_APPS = [ ..., 'myapp.addons.pcpanalysis' ] Also tried 'myapp.addons.pcpanalysis.apps.PcpConfig'. My apps.py: from __future__ import absolute_import from django.apps import AppConfig class PcpConfig(AppConfig): name = "myapp.addons.pcpanalysis" def ready(self): from myapp.addons.pcpanalysis import logic logic.register_events() My handler of event in logic.py is working properly, but when event occur, I get this error: (1146, "Table 'project.myapp.addons.pcpanalysis_node' doesn't exist") I've tried to look into container with database and there are missing only models from my addon, all other models are in DB. I've tried to change names, check everything but seems that has no effect. I also don`t understand that my handler in logic.py and registration in apps.py works properly and there is problem only with models. I will be happy for all tips that I can try. Thank you! P.S. Everything was working properly in Django 1.8, migration to 2.2 changed it. I hadn't changed any settings variables before it occured. -
Can i deserialize a fk object using just the name field?
I have two models - one is a foreign key of the other, I have serializers for each. What I'm trying to accomplish is a way to serialize/deserialize using only the name of the foreign key field, rather than a nested object. The fk field in question is TableAction. My question is how do I define my serializer in order to accomplish this. I think maybe specifically I just need to know which serializer methods to override in order to drop that logic into. When I send a payload, I do not want to send a nested TableAction object, instead I just wanted to send the name of the TableAction. Due to business requirements I cannot change the structure of the payload being sent. models class TableEntry(models.Model): reward_table = models.ForeignKey( RewardTable, related_name="entries", on_delete=models.CASCADE ) action = models.ForeignKey( TableAction, max_length=100, related_name="entries", on_delete=models.CASCADE ) reward_item = models.ForeignKey( RewardItem, related_name="reward_table_entries", on_delete=models.CASCADE ) reward_item_amount = models.PositiveIntegerField() class Meta: unique_together = ("reward_table", "reward_item", "action") class TableActionManager(models.Manager): def get_by_natural_key(self, name, application): return self.get( name=name, application=application ) class TableAction(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) application = models.ForeignKey( Application, related_name="reward_actions", on_delete=models.CASCADE ) objects = TableActionManager() class Meta: unique_together = ("application", "name") def __str__(self): return self.name def natural_key(self): … -
django-datatable-view without a model
I wanted to switch from django-tables2 to a more JS driven table system. My django app however does not have it's own database, but runs on a variety of functions that provide a big number of dicts/json. I wanted to populate my table with data from a dict/json, not from a model - is there a way to do this? -
Not Found: /nurse/articles/10/ Django Rest Framework
I have started learning Django rest Framework.I read an article and tried on my computer.But unable to figure out why am i getting this error. Some one please help me.Thank you models.py class Author(models.Model): name = models.CharField(max_length=255,blank=True,null=True) email = models.EmailField() def __str__(self): return str(self.name) class Article(models.Model): title = models.CharField(max_length=120,blank=True,null=True) description = models.TextField(blank=True,null=True) body = models.TextField(blank=True,null=True) author = models.ForeignKey('Author', on_delete=models.CASCADE,related_name='articles') def __str__(self): return str(self.title) views.py class ArticleView(APIView): def get(self, request,pk=None): try: if pk: allowance=get_object_or_404(Article.objects.all(),pk=pk) print(allowance) serializer = ArticleSerializer(allowance,many=True) return Response({serializer.data}) else: articles = Article.objects.all() serializer = ArticleSerializer(articles, many=True) return Response({"articles": serializer.data}) except Exception as e: print(e) return Response({"success":False,"message":str(e)},status=status.HTTP_400_BAD_REQUEST) def post(self, request): try: article = request.data.get('article') print('Data',article) # Create an article from the above data serializer = ArticleSerializer(data=article) if serializer.is_valid(raise_exception=True): article_saved = serializer.save() return Response({"success": "Article '{}' created successfully".format(article_saved.title)}) except Exception as e: print(e) return Response({"success":False,"message":str(e)},status=status.HTTP_400_BAD_REQUEST) def put(self, request, pk): saved_article = get_object_or_404(Article.objects.all(), pk=pk) data = request.data.get('article') serializer = ArticleSerializer(instance=saved_article, data=data, partial=True) if serializer.is_valid(raise_exception=True): article_saved = serializer.save() return Response({"success": "Article '{}' updated successfully".format(article_saved.title)}) def delete(self, request, pk): # Get object with this pk article = get_object_or_404(Article.objects.all(), pk=pk) article.delete() return Response({"message": "Article with id `{}` has been deleted.".format(pk)},status=204) serializers.py class ArticleSerializer(serializers.Serializer): # class Meta: # model = Article # fields = ('title', 'description', … -
Choosing the database for my Django Project
I'm working on a Django Project for the very first time, also I'm new to programming so I really don't know that much, I'm learning through videos. I'm trying to develop a project management system for a web agency. (That maybe in future will also manage client and their informations and will give the possibility of making invoices). I know that stack overflow is used to make specific and technical question. But I tried to research the things I've doubts on but since I'm new to programming often the answers aren't really clear to me. So I hope you'll accept these post because really I don't know where else to look. I have some questions: How do I make a Django Project secure? Like do I need to be a really skilled programmer to block for example hackers from trying to access to my web app? How do I make sending email through my web app secure? or payments? or the file imported/exported from its users? Some functionalities on some view (like the button to add a new project) should only be available for some type of users, what is the best way of giving users permission? is it using … -
How to save multiple selected data using React Apollo client?
Recently I have started to learn react with Django and GraphQL and I face some problem. I want to create an event member form where I will input event name, description & location and I want to select multiple User and save this event for every user separately. models.py class EventMember(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) event = models.ForeignKey(Event,related_name='events', on_delete=models.CASCADE) create_event_member.js const CreateEventMember = ({classes}) =>{ const [open, setOpen] = useState(false) const [name,setName] = useState("") const [description,setDescription] = useState("") const [locationId,setLocationId] = useState("") const [userId,setUserId] = useState([""]) const handleSubmit = (event,createEventMultipleUsers) =>{ event.preventDefault() createEventMultipleUsers() } return ( <> {/* Create Event Button */} <Button onClick={()=>setOpen(true)} variant="contained" color="secondary"> Add Event Member </Button> <Mutation mutation={CREATE_EVENT_Member} variables={{ name,description,locationId,userId}} onCompleted={ data =>{ console.log({data}); setOpen(false); setName(""); setDescription(""); setLocationId(""); setUserId([""]); }} refetchQueries={() =>[{ query : GET_QUERY }]} > {( createEventMultipleUsers, {loading,error}) =>{ if (error) return <div>Error</div> return( <Dialog open={open} className={classes.dialog}> {/* <listLocation></listLocation> */} <form onSubmit={event=> handleSubmit(event,createEventMultipleUsers)}> <br></br> <DialogTitle>Create Event Member</DialogTitle> <DialogContent> <DialogContentText> Add a event title, Description, location and Users </DialogContentText> <FormControl fullWidth> <TextField label = "name" placeholder="Enter a title for this event" className={classes.textField} onChange={event=>setName(event.target.value)} /> </FormControl> <FormControl fullWidth> <TextField multiline rows="4" label = "Description" placeholder="Enter Description" className={classes.textField} onChange={event=>setDescription(event.target.value)} /> </FormControl> <FormControl fullWidth> <InputLabel htmlFor="grouped-native-select"></InputLabel> <Select native defaultValue="" … -
Serving static files from S3 bucket not working?
I have configured an S3 bucket to store and serve static and media files for a Django website, currently just trying to get the static files needed for the admin pages and all that. Here is all the static and AWS config info in my settings file: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'config.storage_backends.MediaStorage' #used to authenticate with S3 AWS_ACCESS_KEY_ID = 'AKIAWWJOJKZGFSJO2UPW' #not real one AWS_SECRET_ACCESS_KEY = 'KNg1z5wXWiDRAIh4zLiHgbD2N3wtWZTK' #not real one #for endpoints to send or retrieve files AWS_STORAGE_BUCKET_NAME = 'my-static' #not real bucket name AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400',} AWS_LOCATION = 'static' STATIC_ROOT = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'config/static'), ] Of course I replaced any sensitive variables with fake ones for the purpose of this post. I have gone through many tutorials and other posts and I seem to have my STATIC_URL configured correctly but whenever I runserver and go to the admin pages, none of the css is applied. I do not think it is properly retrieving the static files (they are all uploaded to the S3 bucket) from the bucket, but I am stuck on what to do. -
Find if static file exists before calling in deployment - Django
In production I am able to run: #views.py from django.contrib.staticfiles import finders result = finders.find(f'Images/{var}') context = {"r", results} #template.html {% if r %} {% with 'Images/'|add:var as var %} <img src="{% static var %}"> {% endwith %} {% endif %} However, now that my files are being stored in Google's buckets finders.find(f'Images/{var}') keeps returning False and my images aren't being displayed. I need a way to test if files exists prior to calling them to avoid displaying empty boxes when a variable's image does not exist. Any help would be much appreciated, thank you! -
django.db.utils.IntegrityError: UNIQUE constraint failed: authentication_user.email
I am trying create user through an API, But i am struck on above error. Below are the code of the User and its manager. Here, I am creating custom user model. class UserManager(BaseUserManager): def create_user(self,username,email, password=None): if username is None: raise TypeError('Users should have a Username') if email is None: raise TypeError('Users should have a Email') user = self.model(username=username,email=self.normalize_email) user.set_password(password) user.save() return user def create_superuser(self,username,email, password=None): if password is None: raise TypeError('Password should not be none') user = self.create_user(username, email, password) user.save() return user class User(AbstractBaseUser,PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255,unique=True,db_index=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects= UserManager() def __str__(self): return self.email Below is serializers.py file. class RegisterSerializers(serializers.ModelSerializer): password = serializers.CharField(max_length=68, min_length=6, write_only=True) class Meta: model = User fields = ['email','username','password'] def validate(self, attrs): email = attrs.get('email','') username = attrs.get('username','') if not username.isalnum(): raise serializers.ValidationError('The username should only contain alphanumeric character') return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) Here is POST request in views.py class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializers def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data,status=status.HTTP_201_CREATED) I am new to drf. Kindly help me out, thanks. -
Wildcard exclusion of template path for makemessages
I'm writing a management command to automate the ignore paths sent to django's makemessages command. The reason for this is that the project has a directory of themes (html files) and a given theme may only be supported by 1 language. Therefore I want to ignore certain paths for some locales. For example, theme A might be for Japan, and theme B might be for Italy. So ideally I want a management command that does this; class Command(BaseCommand): help = ( "Checks the provided locale to automatically provide the ignored " "paths allowing us to only add certain templates to the po " "files.\n\n" "Django's standard `makemessages` is then called with that ignored " "pattern and the provided locale" ) ignored = { 'ja': [ 'project/templates/themes/b/**/*.html', ], 'it': [ 'project/templates/themes/a/**/*.html', ] } def add_arguments(self, parser): parser.add_argument( '--locale', '-l', default=[], action='append', help='Creates or updates the message files for the given ' 'locale(s) (e.g. pt_BR). ' 'Can be used multiple times.', ) def handle(self, *args, **options): """ Run the command """ locale = options['locale'] locales = set(locale) for code in locales: message_kwargs = { 'locale': [code, ], 'ignore': self.ignored[code] } call_command("makemessages", **message_kwargs) However this doesn't exclude the templates, only if I include … -
Running Python Tests from Subpackages
I've got a package - we'll be creative and call it package - and in there are api and dashboard packages, each with a tests module and various files filled with tests. I'm using Django test runner and rather than having package.api.tests and package.dashboard.tests in my run configs, I'd like to just have package.tests and have that run all the tests in the packages below it. I added a tests package to package and in the init tried a few things like from package.api.tests import * or using an all declaration but that didn't work. Is there a way to make this happen? It's not the most annoying thing in the world, but it's a package that gets brought in to each project we do, and it would just be a bit simpler to have instructions of "Run package.tests", especially if we end up adding more packages beyond api and dashboard. -
Django Formset Not Validating Even When Fields Are Filled
I am working with a formset in django and I am having lots of difficulty getting it to post properly. I am simply receiving an error that not there is not HTTP response, which I understand is happening because I have not provided one when the form is not valid, but my main concern is why is my form not valid when I am in fact filling out the only required field. Below is the code I am working with. It is the TaskGroupDetailForm which is failing to validate: models.py class TaskType(models.Model): name = models.CharField(max_length=100, null=False, blank=False, unique=True) description = models.CharField(max_length=500, null=False, blank=False) def __str__(self): return self.name class TaskGroup(models.Model): name = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name class TaskGroupDetail(models.Model): taskGroup = models.ForeignKey(TaskGroup, null=True, blank=True) taskType = models.ForeignKey(TaskType, null=False, blank=False, on_delete=models.CASCADE) forms.py class CreateTaskGroupForm(forms.ModelForm): class Meta: model = TaskGroup fields = ['name'] class TaskGroupDetailForm(forms.ModelForm): class Meta: model = TaskGroupDetail fields = ['taskType'] #I am assigning the other field, taskGroup, manually in the view views.py def TaskGroupView(request): detailform = modelformset_factory(TaskGroupDetail, TaskGroupDetailForm, can_delete = False) if request.method == "POST": groupform = CreateTaskGroupForm(request.POST) formset = TaskGroupDetailForm(request.POST) print(formset) if groupform.is_valid(): print(formset.errors) if formset.is_valid(): group = groupform.save() details = formset.save(commit=True) for item in details: item.taskGroup … -
text area show in one line in django template
I use Django. My text field was created by RichTextField. In the browser, the text does not break to multiline and exceed from container class like below: References References References References References References References References References References References References References References References References References References References References References References References References References References References I want to show text like this in HTML format: References References References References References References References References References References References References References References References References References References References References References References References References References References References -
delhivery api integration in django python
i'm trying to integrate delhivery api with django. i have the using the test api key its returning 200 with format key missing in POST. i'm not sure what i'm getting wrong import requests shipping_api_token = "api_token" shipping_api_base_url = "https://staging-express.delhivery.com/api/" warehouse_name = "Primary" headers = { "Authorization": f"Token {shipping_api_token}", "Content-Type": "application/json" } def createOrder(orderID="", orderDate="yyyy-mm-dd", billing_name="", billing_address1="", billing_address2="", billing_city="", billing_state="", billing_pincode="", billing_country="", billing_email="", billing_phone="", shipping_is_billing=True, shipping_name="", shipping_address1="", shipping_address2="", shipping_city="", shipping_state="", shipping_pincode="", shipping_country="", shipping_email="", shipping_phone="", Items=[], paymentMethod="Prepaid", subTotal=0, length=0, breadth=0, height=0, weight=0, pickupLocation="Primary"): payload = { "shipment":[{ "add": "M25,NelsonMarg", "phone": 1234567890, "payment_mode": "COD", "name": "anita", "pin": 325007, "order": "847"} ], "pickup_location": { "name": "THE0045874-B2C", "city": "delhi", "pin": 12859, "country": "india", "phone": 7418529638, "add": "address" } } try: url = f"{shipping_api_base_url}/cmu/create.json" response = requests.post(url, json=payload, headers=headers) return response.status_code, response.json() except: return 500, {"message": "Error", "status": "fail"} i'm getting this response: { "cash_pickups_count": 0, "package_count": 0, "upload_wbn": null, "replacement_count": 0, "rmk": "format key missing in POST", "pickups_count": 0, "packages": [], "cash_pickups": 0, "cod_count": 0, "success": false, "prepaid_count": 0, "error": true, "cod_amount": 0 } As i can see from doc it also same error: -
Python + How to merge two dictionaries with same key and value
Sample dictionaries skus = ( {'sku': '53009', 'qtyonhand': '50'}, {'sku': '53004', 'qtyonhand': '20'}, {'sku': '53006', 'qtyonhand': '4'}, {'sku': '53007', 'qtyonhand': '500'}, {'sku': '53010', 'qtyonhand': '20'}, {'sku': '53013', 'qtyonhand': '40'}, {'sku': '53014', 'qtyonhand': '20'}, ) product_skus = [ {'sku': '53009', 'line_id': 75128133}, {'sku': '53004', 'line_id': 75453798}, {'sku': '53006', 'line_id': 75504454}, {'sku': '53007', 'line_id': 75504455}, {'sku': '53010', 'line_id': 75504457}, {'sku': '53013', 'line_id': 75504658}, {'sku': '53014', 'line_id': 75504659}, ] Trying to merge both dictionaries on the basis of the key-value pair. Expected Output: merged_skus = ( {'sku': '53009', 'qtyonhand': '50', 'line_id': 75128133}, {'sku': '53004', 'qtyonhand': '20', 'line_id': 75453798}, {'sku': '53006', 'qtyonhand': '4', 'line_id': 75504454}, {'sku': '53007', 'qtyonhand': '500', 'line_id': 75504455}, {'sku': '53010', 'qtyonhand': '20', 'line_id': 75504457}, {'sku': '53014', 'qtyonhand': '20', 'line_id': 75504659}, {'sku': '53013', 'qtyonhand': '40', 'line_id': 75504658}, ) -
How can I POST a new item if "Author" hasn't been created yet?
I'm creating an app to catalog records using React for the Front End and Django+REST Frameworks for the Backend. I'm using HyperlinkedModelSerializer, and it seems I can't create a new record unless the artist has already been created (I'll get an error letting me know ID field can't be null). I then have to include the artist and artist ID if I want to create a new record. I'll copy some of my code below for reference. Thanks in advance for your help! models.py from django.db import models # Create your models here. class Artist(models.Model): name = models.CharField(max_length=100) notes = models.TextField(blank=True, null=True) photo_url = models.TextField(blank=True, null=True) def __str__(self): return self.name class Album(models.Model): title = models.CharField(max_length=100) artist = models.ForeignKey( Artist, on_delete=models.CASCADE, related_name='albums') release_date = models.DateField(blank=True, null=True) acquired_date = models.DateField(blank=True, null=True) genre = models.CharField(max_length=100, blank=True, null=True) label = models.CharField(max_length=100, blank=True, null=True) # songs = models.ForeignKey( # Song, on_delete=models.CASCADE, related_name='songs') notes = models.TextField(blank=True, null=True) photo_url = models.TextField(blank=True, null=True) def __str__(self): return self.title class Song(models.Model): title = models.CharField(max_length=100, default='Song title') track = models.CharField(max_length=100, blank=True, null=True) artist = models.ForeignKey( Artist, on_delete=models.CASCADE, related_name='songs') album = models.ForeignKey( Album, on_delete=models.CASCADE, related_name='songs') song_url = models.TextField(blank=True, null=True) class Meta: unique_together = ['album', 'track'] ordering = ['track'] def __str__(self): return f'{self.track} … -
Why is my SIGNAL not working in Django - what I'm doing wrong?
first of all, I'm not a developer. Trying to build an Application with Django (Version 3.1.2) but facing some issues with signals. I have this Models in my models.py: class PhoneNumbers(models.Model): number = models.CharField(_('Category'), max_length=255) created = models.DateTimeField(_('Created'), auto_now_add=True, blank=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) and a Model Persons class Persons(models.Model): name = models.CharField(_('Name'), max_length=255) number = models.CharField(_(Number), max_length=255) ... The code in my signals.py: from django.db.models.signals import pre_save, post_delete, post_save from django.dispatch import receiver from .models import PhoneNumbers, Persons @receiver(post_save, sender=Persons) def save_contract(instance, sender, created, **kwargs): print("Request finished!") When I save a Person I expect to get a PRINT in the console output, but get nothing. What is wrong? I also add in __init__.py: default_app_config = 'myapp.apps.MyAppConfig' My apps.py looks like: from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' -
How to Add, delete, friend request in django?
#Forms.py ( I have added the form for edit the user profile ) How to Add friend , Delete friend, Send friend request, delete friend in django ? -
DRF "Unauthorized: <route>" when Authorization header is present from React FE
I'm working on integration with Azure AD. I have my ReactJS FE getting the accessToken and now I need to send it to the Django/DRF BE to authenticate it there as well. At any rate, I'm sending the token as a Authorization: "Bearer <token>" and I'm getting a Unauthorized: <route> response. If I comment it out, the request goes through. I'm just trying to understand a couple things: The presence of the Authorization header is obviously telling DRF it needs to do something with it. Does something need to be enabled in DRF settings to handle it? Should I be sending this accessToken to my API in the headers, or the body, of the POST request? // Authentication.js ... const testApiAuthentication = async () => { let accessToken = await authProvider.getAccessToken(); setAccessToken(accessToken.accessToken); if (accessToken) { setAuthenticatingToken(true); axios({ method: 'post', url: '/api/users/', headers: { Authorization: 'Bearer ' + accessToken, }, }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } }; ... # views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import AllowAny # Create your views here. class TestView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): print(request) return Response('Hello World') -
Using default with foreignkey model in django
I'm working on a django project where I have 3 models -category -subcategory -product The subcategory is a foreignkey to the category while the product is a foreignkey to both the category and products When I run migrations, I get the error: django.db.utils.IntegrityError: The row in table 'shop_product' with primary key '5' has an invalid foreign key: shop_product.subcategory_id contains a value '1' that does not have a corresponding value in shop_subcategory.id. Models.py from django.db import models from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = "categories" def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='subcategories', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'subcategory' verbose_name_plural = 'subcategories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = RichTextField(blank=True, null=True) subcategory = models.ForeignKey(Subcategory, related_name='product', on_delete=models.CASCADE, null=True, default=1) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', … -
django if statement has an error. What should I fix?
a.html <div> {%for r in rank%} {%if r.nickname==nickname%} <div style="color: aqua;">{{r.nickname}}</div> {%else%} <div>{{r.nickname}}</div> {%endif%} <hr> {%endfor%} </div> views.py def ranking(request): user = request.user rank = Profile.objects.all().order_by('-user_test_point') profile_obj = Profile.objects.get(user=user) nickname = profile_obj.nickname context = {"rank": rank, "nickname": nickname} return render(request, "a.html", context) I want to change the color if the nicknames of the current user and the ones in the context are the same. Context contains the nicknames of users. But error is "Could not parse the remainder: '==nickname' from 'r.nickname==nickname'" -
How to solve this error ERROR: Command errored out with exit status 1: command: 'c:\users\sanid\appdata\local\pr
**This happened when i tried to install mysqlclient via typing pip install mysqlclient ** earlier also i had an error which i solved by installing Visual studio c++ , But what should i do ???? I also saw some solutions but they don't seem to work so if anyone can tell what to do, Please explain in detail as i am new to programming Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\sanid\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\sanid\\AppData\\Local\\Temp\\pip-install-koqe6sxg\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\sanid\\AppData\\Local\\Temp\\pip-install-koqe6sxg\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sanid\AppData\Local\Temp\pip-wheel-j4e3bxnr' cwd: C:\Users\sanid\AppData\Local\Temp\pip-install-koqe6sxg\mysqlclient\ Complete output (29 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\bin\HostX86\x86\cl.exe …