Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show a value with query_set in a serializer using Django rest framework?
I am making an API and want to list all choices of a model for who use it. # ------------------------------------------------------------- # Image category serializer # ------------------------------------------------------------- class ImageCategorySerializer(serializers.ModelSerializer): #category = CategorySerializer() category = serializers.PrimaryKeyRelatedField( many=True, queryset=Category.objects.all(), ) image = serializers.IntegerField(source="image.id") class Meta: fields = '__all__' model = ImageCategory # ------------------------------------------------------------- # Category # ------------------------------------------------------------- class Category(models.Model): """ This model define a category Args: category (datetime): creation date created_at (str): description of the image """ class CategoryChoice(models.TextChoices): """ This inner class define our choices for several categories Attributes: VIDEOGAMES tuple(str): Choice for videogames. ANIME tuple(str): Choice for anime. MUSIC tuple(str): Choice for music. CARTOONS tuple(str): Choice for cartoons. """ VIDEOGAMES = ('VIDEOGAMES', 'Videogames') ANIME = ('ANIME', 'Anime') MUSIC = ('MUSIC', 'Music') CARTOONS = ('CARTOONS', 'Cartoons') category = models.CharField(max_length=15, choices=CategoryChoice.choices, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) This is shown I want to replace the "Category object('number')" options by the choices of Category model(VIDEOGAMES, ANIME, MUSIC and CARTOONS). -
How to use widget in wagtail admin models.CharField
I have a forms.CharField that uses a widget, as follows: address = forms.CharField( required=False, max_length=100, label="Address", error_messages={'required': ERROR_MSG}, widget=... # <-- this line ) ) I need to use a widhet in a models.CharField, but I am getting errors saying that it doesn't accept widget. like this: address = models.CharField( required=False, max_length=100, label="Address", error_messages={'required': ERROR_MSG}, widget=... # <-- this line ) ) How can I use widget inside models.CharField? -
Django postgress Integer Arrayfield not accepting array
I have suddenly started getting an error with a postgres integer array field in Django I get data from an external API. The field comes in as a string of comma-separated values. In my models.py I have: from django.contrib.postgres.fields import ArrayField ... postcodes = ArrayField(models.IntegerField(null=True, blank=True), null=True) When I process the data I try to clean it up with this method which should dump bad data and only return a list of ints (I hope...): def postcodeExtractor(self,postcode_entry): try: postcodes = list(map(int, postcode_entry.split(','))) , # try covert to a list except: postcodes = [] return postcodes This has been working for months on my test server with a test copy of the live server, but when I started calling the real external API I started catching errors like the following when trying to save new entries, only blank entries are getting saved: Field 'postcodes' expected a number but got [2176, 2168, 2178, 2179, 2555, 2200, 2200, 2565]. Error from the uncaught exception stack: The above exception (int() argument must be a string, a bytes-like object or a real number, not 'list') was the direct cause of the following exception: I can't see what's changed between my local and remote external API. … -
dajango pdf media files not displaying in my web page
I have been looking in the internet all over the place for this and it seems that everything is in check, also media images are very well displayed settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' X_FRAME_OPTIONS = 'SAMEORIGIN' show_pdf.html <iframe src="{{pdf.url}}" frameBorder="0" scrolling="auto" height="1200px" width="1200px" ></iframe> models.py class File_pdf(models.Model): title = models.CharField(max_length=50) pdf = models.FileField(upload_to='portfolio/pdfs') main_resume = models.BooleanField(default=False,help_text="set only one pdf as the main pdf for the main page") def __str__(self): return self.title urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('portfolio.urls')), path('blog/',include('blog.urls')) ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py def pdf_view(request,pdf_id,resume): dic = {} if resume == "yes": pdf_files = File_pdf.objects.filter(main_resume=True) pdf_file = pdf_files[0] dic['pdf'] = pdf_file.pdf dic['title'] = pdf_file.title else: pdf_files = get_object_or_404(File_pdf,pk=pdf_id) pdf_file = pdf_files[0] dic['pdf'] = pdf_file.pdf dic['title'] = pdf_file.title the error looks like this: this is actually the correct link -
Can this be done with Django Admin?
I have a model of ingredients that displays the "serving and weight" options for each ingredient in admin The IngredientAdmin is "inline" in MealAdmin. I am trying to also show the "serving and weight" options for each ingredient. Can this be done in admin? models.py class Meal(models.Model): meal_name = models.CharField(max_length=200, blank=False) meal_image_url = models.CharField(max_length=200, default="") ingredient = models.ForeignKey(Ingredient, on_delete=DO_NOTHING, related_name="mealingredient") def __str__(self): return f'{self.meal_name}' class Ingredient(models.Model): food_code = models.IntegerField(default=0) language = models.CharField(max_length=2, choices=LANGUAGE_CHOICES, default='en') water_g = models.DecimalField(decimal_places=3, max_digits=10, default=0) modifier = models.ManyToManyField(IngredientFoodPortion) class Meta: ordering = ['item_description'] def __str__(self): return f'{self.item_description}' objects = models.Manager() And the admin.py i tried geting the ingredient_id to use it for filtering in both Admin classes, but it always comes back empty in both: class IngredientAdmin(admin.ModelAdmin): my_id_for_formfield = None def get_form(self, request, obj=None, **kwargs): if obj: self.my_id_for_formfield = obj.food_code return super(IngredientAdmin, self).get_form(request, obj, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "serving": kwargs["queryset"] = IngredientFoodPortion.objects.filter(food_code=self.my_id_for_formfield).distinct() return super(IngredientAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Ingredient, IngredientAdmin) class MealAdmin(admin.ModelAdmin): my_id_for_formfield = None def get_form(self, request, obj=None, **kwargs): if obj: self.my_id_for_formfield = obj.food_code return super(MealAdmin, self).get_form(request, obj, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "serving": kwargs["queryset"] = IngredientFoodPortion.objects.filter(food_code=self.my_id_for_formfield) return super(MealAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Meal, MealAdmin) Thanks in advance... -
An Integer is required (got type NoneType)
I am using DatetimeField in my Model and I am trying to output time format within my strftime. The problem is I am getting this error "an Integer is required (got type NoneType)" This is my code. unique_upload_by_dates: List[str] = [ datetime.datetime(day=day, month=month, year=year).strftime("%m %d, %Y") for month, day, year in Upload.objects.all() .values_list( "date_of_upload", "date_of_upload__day", "date_of_upload__year", ) .order_by("date_of_upload") .distinct() ] -
Trying to the webhook with django. But it dosen't work
I'm Trying to the webhook with django. But it dosen't work. Is something wrong? recieved side of the page which is expecetd reload or updated by recieving POST request dosen't work at part the code below. return HttpResponse("RecievedData=" + s) I just want to imform the data and update the recieved side page. [project.url] from django.contrib import admin from django.urls import path, include from webhook.views import webhook urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), path('webhook/', webhook), ] [app-urls.py] ...... sender side from django.urls import path from . import views app_name= "app" urlpatterns = [ path('', views.IndexView.as_view(), name="index"), path('pos/', views.pos, name="pos") ] [app-views.py] ... sender side from django.shortcuts import render, redirect from django.views import generic import requests class IndexView(generic.View): template_name= "app/index.html" def get(self, request, *args, **kwargs): return render(request, self.template_name) def pos(request): url= 'http://127.0.0.1:8000/webhook/' dt= {"foo": "bar"} r1= requests.post(url,dt) print("pos", r1) return redirect('app:index') [webhook-views.py] ... reciever side from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def webhook(request): s="" if request.method == 'POST': s= request.POST.get("foo") return HttpResponse("RecievedData=" + s) # <-------- Here. [app-index.html] ... sender side <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <a href="{% url 'app:pos' %}">Post Data</a> </body> </html> -
For loop not showing on template
i'm trying to display the news on my website but for some reason its not showing, the first loop is ok, but the second one is not displaying anything where it suposed to be. Here are my code: HTML: <div class="container-fluid"> <div class="container"> <div class="row"> {% for cat in cats %} <div class="col-lg-6 py-3"> <div class="bg-light py-2 px-4 mb-3"> <h3 class="m-0">{{cat.category_name}}</h3> </div> <div class="owl-carousel owl-carousel-3 carousel-item-2 position-relative"> {% for news in category.news_set.all %} {% if forloop.counter == 4 %} <div class="position-relative"> <img class="img-fluid w-100" src="{{news.cover.url}}" style="object-fit: cover;"> <div class="overlay position-relative bg-light"> <div class="mb-2" style="font-size: 13px;"> <a href="">{{news.title}}</a> <span class="px-1">/</span> <span>{{news.created_at}}</span> </div> <a class="h4 m-0" href="">{{news.description}}</a> </div> </div> {% endif %} {% endfor %} </div> </div> {% endfor %} </div> </div> views.py: def home (request): cats = Category.objects.all()[0:4] articles = Article.objects.all() return render (request,'pages/home.html', context={ 'articles': articles, 'cats': cats, }) -
Django Delete duplicates rows and keep the last using SQL query
I need to execute a SQL query that deletes the duplicated rows based on one column and keep the last record. Noting that it's a large table so Django ORM takes very long time so I need SQL query instead. the column name is customer_number and table name is pages_dataupload. I'm using sqlite. -
Django: unable to save model - Err: "id" expected a number but got <django.db.models.fields.related.ForeignKey...>
I'm really out of ideas here, I tried everything. Basically I'm just trying to save some item whereas the owner is a foreign key related to the default Django User Model. This same methods works for other views and models, where the association is identically. But here I get this error: Exception Type: TypeError Exception Value: Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: owner>. This is my model: class User(AbstractUser): pass """ ... """ class Item(TimeStampMixin): title = models.CharField(max_length=40) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Items") etc=etc... This is my view: class Form_New_Item(ModelForm): class Meta: model = Item fields = ['title', 'description', 'price', 'category', 'image_url'] def create_new_item(request): if request.user.is_authenticated and request.method == "POST": form = Form_New_Item(request.POST) user = request.user if form.is_valid(): new_item = Item( owner=user, title=form.cleaned_data['title'], ecc=ecc, ) new_item.save() return HttpResponseRedirect(reverse("index")) Notice the error happens when I call new_item.save(): Thank you in advance for any help you can provide me. -
Run autopep8 on all python files except migrations doable?
Am wondering is there a way to run autopep8 command on all python files exept the migrations? To fix all pep8 errors. Instead of doing the command autopep8 --in-place --aggressive --aggressive <filename> -
how to pass variables between functions Django?
I have a function like this in views.py: def signin(request): if request.method == 'POST': uname = request.POST['username'] pwd = request.POST['password'] #and other code And then i have another function like this: def reservations(request): try: c = Utilisateur.objects.get(username = uname) reserve = Reserve.objects.get(client = c) return render (request, 'reservation.html', {'reserve':reserve}) except: return HttpResponse ('you have no reservations!') And i want to use the "uname" variable of the first function but it doesn't work any solution? -
what does models.Models.None mean in django templates?
I have three models. A User model, which is just the basic django User model, so I won't add the code for it. An Account model (which is a CustomUser model/extension of the basic django User): class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group) And, finally, I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.TextField() topic = models.CharField(max_length=55) joined = models.ManyToManyField(User, related_name='joined_group') def __str__(self): return self.topic Now I'm trying to render my User information as well as the Account information in my django templates. Inuser_details.html I have the following account info written out: <div>Username: {{user.username}}</div> <div>Groups Joined: {{user.account.joined_groups}}</div> However, what's rendering is Groups Joined: groups.Group.None I don't really know what this means or why it's happening, and I also don't know how to render the Groups my User has joined. Any help would help. Thanks. -
ValueError --The view dashboard.views.saveBlogTopic didn't return an HttpResponse object. It returned None instead
I got this error when i tried to test my function inside views.py: Traceback (most recent call last): File "/home//lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home//lib/python3.8/site-packages/django/core/handlers/base.py", line 204, in _get_response self.check_response(response, callback) File "/home/**/lib/python3.8/site-packages/django/core/handlers/base.py", line 332, in check_response raise ValueError( ValueError: The view dashboard.views.saveBlogTopic didn't return an HttpResponse object. It returned None instead. I tried several ways to solve the problem but i couldn't .Can you help me here here are my files: views.py : @login_required def blogTopic(request): context = {} if request.method == 'POST': blogIdea = request.POST['blogIdea'] request.session['blogIdea'] = blogIdea keywords = request.POST['keywrods'] request.session['keywrods'] = keywords audience = request.POST['audience'] request.session['audience'] = audience blogTopics = generateBlogTopicIdeas(blogIdea, audience, keywords) if len(blogTopics) > 0: request.session['blogTopics'] = blogTopics return redirect('blog-sections') else: messages.error(request,"Oops we could not generate any blog ideas for you, please try again.") return redirect('blog-topic') return render(request, 'dashboard/blog-topic.html', context) @login_required def blogSections(request): if 'blogTopics' in request.session: pass else : messages.error(request,"Start by creating blog topic ideas") return redirect('blog-topic') context = {} context['blogTopics'] = request.session['blogTopics'] return render(request, 'dashboard/blog-sections.html', context) @login_required def saveBlogTopic(request, blogTopic): if 'blogIdea' in request.session and 'keywords' in request.session and 'audience' in request.session and 'blogTopics' in request.session: blog = Blog.objects.create( title = blogTopic, blogIdea = request.session['blogIdea'], keywrods = request.session['keywrods'], … -
Django REST Framework router seems to be overriding my explicitly defined path in URLpatterns
new to coding so I'm sure this is a simple problem but I can't seem to figure it out. I've abbreviated the code so it's simpler to see the problem. urls.py router = routers.DefaultRouter() router.register(r'clients', views.ClientViewSet, basename='client') urlpatterns = [ #Bunch of other paths here. path('client/<int:pk>/contacts', login_required(views.contacts_by_client), name="client-contacts"), path('api/', include(router.urls)), ] views.py def contacts_by_client(request, pk): client = Client.objects.get(id=pk) contact_list = Contact.objects.filter(user=request.user, client=pk) context = { 'contacts': contact_list, 'client': client } return render(request, 'pages/contacts-client.html', context) class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=True, methods=['get'], name="Contacts") def contacts(self, request, pk=None): # Bunch of code here. My suspicion is that the router is creating a route name called "client-contacts" based on the action created in views.py, however, I don't understand why it would take precedence over the explicitly labeled url pattern that comes before it. I know I must be missing something super simple, but I can't figure it out. Thank you all for your help! -
Update data in db django after reload page with discord auth
I make authorize with my discord, when user auth I save data to my database but when user changes his nickname in discord, I dont get new version of nickname in database, how to fix this? -
Django: how to create slugs in django?
i want to create a slug in django, i have used the slug = models.SlugField(unique=True). Now when i create a post with a slug of learning-to-code it works, but if i create another post with the same slug learning-to-code, it shows an error like Unique Constraint Failed. But i want to create posts with the same slug, is there a way to make slugs unique only to the time a post was created? this is how my model looks class Article(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) slug = models.SlugField(unique=True) user = models.ForeignKey('userauths.User', on_delete=models.SET_NULL, null=True) How can i go about achieving this? -
How can I add required attribute?
I would like to add the required attribute in the product_title field. How can I do It? class add_product_info(forms.ModelForm): product_desc = RichTextField() class Meta: model = Products fields = ('product_title') labels = {'product_title':'Title'} widgets = { 'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'}) } -
Struggling with aggregate and subtraction in Django and PostgreSQL
So I am having an issue with querys (getting the sum of an item(aggregate) and subtracting. What I am trying to do is 10 (soldfor) - 2 (paid) - 2 (shipcost) = 6 The issue is, if I add another (soldfor) (paid) or (shipcost) = it will add all of them up so the profit becomes double. Another example, If I have an item with the (paid) listed at 3.56 and another item with the same (paid) int, it subtracts the two from each new row. I have tried two queries and I cannot get them to work. What I get: 10 (soldfor) - 2 (paid) - 2 (shipcost) = 12, because two fields have the same exact input. So basically, if the two fields have the same number it adds or subtracts them to every row that have the same field with the same number. models.py class Inventory(models.Model): product = models.CharField(max_length=50) description = models.CharField(max_length=250) paid = models.DecimalField(null=True, max_digits=5, decimal_places=2) bin = models.CharField(max_length=4) listdate = models.DateField(null=True, blank=True) listprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) solddate = models.DateField(null=True, blank=True) soldprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) shipdate = models.DateField(null=True, blank=True) shipcost = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def … -
Query Django data base to find a column with a specific value and update that column value
I have tried very hard to understand how to update my data base, but struggling to even print out the value of the data returned. My code in views.py: #SET THE PLACEHOLDER DATE AND TIME AS A STRING AND CONVERT TO DATETIME #QUERY THE DATA BASE TO FIND THE ROW WHERE END_END_TIME = PLACEHOLDER DATE AND TIME #OUTPUT THE DATA TO THE TERMINAL #UPDATE THE END_DATE_TIME TO CURRENT DATE AND TIME date_time_placeholder = "2023-01-01 12:00:00" datetime.strptime(date_time_placeholder, "%Y-%m-%d %H:%M:%S").date() get_value = logTimes.objects.get(end_date_time = date_time_placeholder) print(get_value) The output: logTimes object (155) I can see in the admin site the code is working, it is finding the correct row, but I am not sure how to print the column data to the terminal instead of the just the object and ID. What I am trying to achieve ultimately is to update the end_date_time in this row to the current date and time using datetime.now(), I am not having any success, not for the lack of trying for hours. Any help is appreciated. -
Django Python LoadData: Error Problem Installing Fixture
First i have migrate and makemigrations and then I have dump data with this command : python manage.py dumpdata --exclude auth.permission --exclude contenttypes > dvvv.json and i have tried to flush database and when i put python manage.py loaddata dvvv.json it says this: pymysql.err.ProgrammingError: (1146, "Table 'webcnytc_prilert_tool.Prilert_confirmationemail' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 78, in handle self.loaddata(fixture_labels) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 123, in loaddata self.load_label(fixture_label) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 190, in load_label obj.save(using=self.using) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/serializers/base.py", line 223, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 778, in save_base force_update, using, update_fields, File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 859, in _save_table forced_update) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 912, in _do_update return filtered._update(values) > 0 File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/query.py", line 802, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1559, in execute_sql cursor = super().execute_sql(result_type) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute return … -
DRF Add annotated field to nested serializer
I have two serializers that represent comments and their nested comments. I'm provide a queryset to viewset with annotated field likes. But my problem is that field only working in parent serializer. When i add this field to nested serializer i got error Got AttributeError when attempting to get a value for field likes on serializer CommentChildrenSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Comment instance. Original exception text was: 'Comment' object has no attribute 'likes'. Here is some my code. Thanks Models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) body = models.TextField() tags = TaggableManager(blank=True) pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pub_date'] class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(max_length=500) pub_date = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='children') class Meta: ordering = ['-pub_date'] class Vote(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) choice = models.BooleanField(null=True) Serializers.py class PostRetrieveSerializer(PostSerializer): comments = CommentSerializer(read_only=True, many=True) author = AuthorInfoSerializer(serializers.ModelSerializer) class Meta: model = Post fields = ['id', 'author', 'slug', 'title', 'body', 'tags', 'pub_date', 'comments'] class CommentChildrenSerializer(serializers.ModelSerializer): author = AuthorInfoSerializer(read_only=True) likes = serializers.IntegerField() class Meta: model = Comment fields … -
Saas cannot find stylesheet to import. Django project
I am trying to use bootstrap saas in my django project. I installed saas and bootstrap via npm sucessfully however when I try to compile my sass/scass to css I get an error below. I think i am somehow getting file directories incorrect project structure Error -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__product_product.brand_id
I am preparing an ecommerce project in Django. Now I'm trying to change some things When I run the python manage.py makemigrations and python manage.py migrate commands, I get an error that I can't understand. error django.db.utils.IntegrityError: UNIQUE constraint failed: new__product_product.brand_id models.py class Brand(models.Model): name = models.CharField(max_length=10) image = models.ImageField(upload_to='brand') slug = models.SlugField(max_length=15, unique=True) date = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return self.name class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) main_image = models.ImageField(upload_to='product_images/%Y/%m/%d/') detail = models.TextField() keywords = models.CharField(max_length=50) description = models.CharField(max_length=1000) price = models.FloatField() #brand = models.CharField(max_length=50, default='Markon', verbose_name='Brand (Default: Markon)') brand = models.ForeignKey(Brand, on_delete=models.DO_NOTHING, default='Markon') sale = models.IntegerField(blank=True, null=True, verbose_name="Sale (%)") bestseller = models.BooleanField(default=False) amount = models.IntegerField(blank=True, null=True) available = models.BooleanField(default=True) stock = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) used = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) -
What authentication actually does? [closed]
Let's say I'm building a web application and I can choose between 2 different ways of authenticating users. Outcome is same(same record in database, same user experience), but when I look how both ways are written I can see plenty of differences. I would want to know what could be differences between the 2 ways and should I choose more or less complicated.