Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Reverse for not found. 'account_profile' is not a valid view function or pattern name
Учу Django. Я работаю над своим проектом для курса, и сейчас я полностью застрял. Трудно что-то мне даются эти urls. Прошу помощи. Проблема с urls. Подскажите где я не правильно сделал. Вот такая ошибка: Reverse for 'account_profile' not found. 'account_profile' is not a valid view function or pattern name. urls.py from django.urls import path, include from .views import AccountProfile, UpdateProfile, auth_code urlpatterns = [ path('profile', AccountProfile.as_view(), name='account_profile'), path('edit', UpdateProfile.as_view(), name='account_edit'), path('auth_code', auth_code, name='auth_code'), path('', include('allauth.urls')), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'news', 'protect', 'django_filters', 'django.contrib.flatpages', 'django_apscheduler', 'board', 'accounts', 'bootstrap4', 'ckeditor', 'ckeditor_uploader', ] NoReverseMatch at /index Reverse for 'account_profile' not found. 'account_profile' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/index Django Version: 4.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'account_profile' not found. 'account_profile' is not a valid view function or pattern name. Exception Location: E:\D6\venv\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: board.views.Index Python Executable: E:\D6\venv\Scripts\python.exe Python Version: 3.9.13 Python Path: ['E:\\D6', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\python39.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\marsh\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'E:\\D6\\venv', 'E:\\D6\\venv\\lib\\site-packages'] Server time: Sun, 19 Mar 2023 20:34:10 +0000 Error during template rendering In template E:\D6\templates\default.html, error at line 30 Reverse … -
NoReverseMatch at Reverse for '{}' with arguments '('',)'.: ['(?P<id>[0-9]+)/\\Z']
NoReverseMatch at /Bookstore/book_detail/7/ Reverse for 'edit_book' with arguments '('',)' not found. 1 pattern(s) tried: ['Bookstore/edit_book/(?P[0-9]+)/\Z'] url.py path('edit_book/int:id/', views.edit_book, name = 'edit_book'), # delet book url path('delete_book/<int:id>', views.delete_book, name = 'delete_book') View.py def edit_book(request, id): book = Book.objects.get(id =id) form = EditBookForm(instance = book) if request.method == 'POST': form = EditBookForm(request.POST, request.FILES, instance = book) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'update_book.html', context) for deleting the book, takes id as an argument def delete_book(request, id): # getting the book to be deleted book = Book.objects.get(id=id) # checking if the method is POST if request.method == 'POST': # delete the book book.delete() # return to home after a success delete return redirect('home') context = {'book': book} return render(request, 'delete_book.html', context) The template file is here template html Error show in these line of code Edit Delete any one help in finding the solution it face noreverse error in the question -
calling a url with reverse with query string during unit testing
I have this URL that i want to test: urlpatterns = [ path('produce<str:code>', ProduceSpreadSheet.as_view(), name="produce" ), ] my test is: class ProduceSpreadSheetTest(TestCase): def setUp(self): self.code = "abcd" def test_valid_token(self): url = reverse('produce', query_kwargs={'code': self.code}) response = client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) I get the error: TypeError: reverse() got an unexpected keyword argument 'query_kwargs' when I change query_kwargs to kwargs: I get the error: TypeError: get() got an unexpected keyword argument 'code' The method to be tested is: class ProduceSpreadSheet(APIView): def get(self, request): code = request.query_params.get('code',None) // continue I want to call it with .../produce?code=abcd query_kwargs and kwargs and reverse('produce') + 'code=code' -
TypeError: load() missing 1 required positional argument: 'f'
I am using MacPro M1 Pro chip Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU. How to solve this issue/ What change is to be made to help me to execute the following command: python pc_certification.py --model resnetv2_50x1_bit_distilled_cutout2_128 --dataset imagenette --num_img -1 --num_mask 6 --patch_size 32 import torch import torch.backends.cudnn as cudnn import numpy as np import os import argparse import time from tqdm import tqdm import joblib from utils.setup import get_model,get_data_loader from utils.defense import gen_mask_set,double_masking_precomputed,certify_precomputed parser = argparse.ArgumentParser() parser.add_argument("--model_dir",default='checkpoints',type=str,help="directory of checkpoints") parser.add_argument('--data_dir', default='data', type=str,help="directory of data") parser.add_argument('--dataset', default='imagenette',type=str,choices=('imagenette','imagenet','cifar','cifar100','svhn','flower102'),help="dataset") parser.add_argument("--model",default='vit_base_patch16_224',type=str,help="model name") parser.add_argument("--num_img",default=-1,type=int,help="number of randomly selected images for this experiment (-1: using the all images)") parser.add_argument("--mask_stride",default=-1,type=int,help="mask stride s (square patch; conflict with num_mask)") parser.add_argument("--num_mask",default=-1,type=int,help="number of mask in one dimension (square patch; conflict with mask_stride)") parser.add_argument("--patch_size",default=32,type=int,help="size of the adversarial patch (square patch)") parser.add_argument("--pa",default=-1,type=int,help="size of the adversarial patch (first axis; for rectangle patch)") parser.add_argument("--pb",default=-1,type=int,help="size of the adversarial patch (second axis; for rectangle patch)") parser.add_argument("--dump_dir",default='dump',type=str,help='directory to dump two-mask predictions') parser.add_argument("--override",action='store_true',help='override dumped file') args = parser.parse_args() DATASET = args.dataset MODEL_DIR = os.path.join('.',args.model_dir) DATA_DIR = os.path.join(args.data_dir,DATASET) DUMP_DIR = os.path.join('.',args.dump_dir) if not os.path.exists(DUMP_DIR): … -
Why Python multiprocessing Pool context manager __exit__ does not close and join
Python's multiprocessing Pool context manager exit calls .terminate(), but a very common pattern that does not use context manager is p = Pool() p.map(do) p.close() p.join() I know that map blocks, and therefore when done in a context manager, there isn't a need to call .close() and .join() (or is it actually better to call them?): with Pool() as p: p.map(do) I also know that .close() and .join() are useful for non-blocking usages e.g. apply_async. If there are some other important reasons to call .close() then .join(), why isn't it in the exit call of Pool context manager? If there are no other benefits, shouldn't we do the following instead: p = Pool() p.map(do) p.terminate() -
AsyncIO for loop conversion
I am new with AsyncIO. I want some help converting the below scenario. I have a set of json files, these will be read and pass it to the post request. This operation does sequentially N number of times I want to covert the below to use parallelism using AsyncIO to do the operation asynchronously. def test(n): num = 0 for names in os.list(dir): filename = os.path.join(.,b=name) while num> n: request.post(url, filename) num = +1 This code runs for all json files sequentially. Can some one help me write the code in asynchronous way that one thread will be running one with 1st json file and if there is any ideal cpu it should run with 2nd json and go on I am new to this. Can anyone help me with this code approach. Thank you -
Playsound module is not running in vs code
how to fix the Error 259 in vs code i tried each and evry way possible to run this code but still not able to run this code. -
Tensorflow sampled_softmax_loss inside model.fit() loss function
I am trying to create a custom word2vec model. To speed up the training process, negative sampling is usually used. There is the function tf.nn.sampled_softmax_loss for this purpose, it requires inputs as a parameter, which apparently is the output of the layer before the softmax layer. This question addresses this, however it doesn't seem possible to use tf.nn.sampled_softmax_loss in a custom loss function, since you only have y_true and y_pred and not the input or output from hidden layers. Is there a way to still get inputs from the context of a custom loss function? This is a snippet from my code (currently not working because of the wrong inputs argument): def sampledLoss(y_true, y_pred): outputWeights, outputBias = self.model.layers[2].weights print(tf.transpose(outputWeights).shape, outputBias.shape, tf.reshape(tf.argmax(y_true, 1), (-1, 1)).shape, y_pred.shape) return tf.nn.sampled_softmax_loss(tf.transpose(outputWeights), outputBias, tf.reshape(tf.argmax(y_true, 1), (-1, 1)), y_pred, 5, vocabulary.vocabSize, num_true = 1) self.model.compile(optimizer="adam", loss=sampledLoss) self.model.fit(trainGen, epochs=epochsAmount) -
Axios network error with vue.js when calling API endpoint
I'm making an API call using axios to my backend server in Django from my Vue.js web app. However, I'm getting the following error on Chrome. (https://i.stack.imgur.com/uq8OG.png) (https://i.stack.imgur.com/nOFNk.png) I suspect it may be a CORS error, but I'm not sure how to deal with this properly on Vue. My code looks like this: async RecentListingsList() { await axios .get("/api/v1/recent-listings/") .then(response => { this.recentListings = response.data }) .catch(error => { console.log(error) }) } I tried using a proxy in package.json and vue.config.js, but this didn't have any effect. I also tried changing the CORS_ALLOWED_ORIGINS setting in settings.py in my Django app. Not sure what else to do. -
Django Modelform DecimalField drop trailing 0s for display, up to 2 decimal places
I have a Modelform that contains multiple DecimalFields with decimal_places=4. I need 4 decimal places as that is a reflection of the underlying data. This is a financial utility where mean values might consume all 4 decimal places. Users should be allowed to enter up to 4 decimal places, and forms should be displayed with up to 4 decimal places. I am not looking for any sort of rounding or truncation. What I want to do is limit the display of trailing 0s in modelforms being rendered in my template, up to a minimum of 2 trailing 0s, as these are dollars. For instance: 3.1234 would still remain as 3.1234 3.1230 would become 3.123 3.1200 would become 3.12 3.1000 would become 3.10 3.0000 would become 3.00 I have came up with the following inside my modelforms init method: def __init__(self, *args, **kwargs): if self.initial: for field_name, field in self.fields.items(): if isinstance(field, forms.DecimalField) and field.decimal_places == 4 and self.initial.get(field_name): self.initial[field_name] = self.initial[field_name].normalize() Using the .normalize() drops ALL the trailing 0s (3.0000 -> 3), however, I want a minimum of 2. I thought of using .quantize(), to enforce a minimum of 2 decimal places, but this rounds values with more then 2 … -
unable to get video feed from camera using opencv in django web app
I have created a django web app and written code to get video feed from my laptop camera using opencv. def start(request): print("HI") def testDevice(source): cap = cv2.VideoCapture(source) if cap is None or not cap.isOpened(): print('Warning: unable to open video source: ', source) testDevice(0) # no printout testDevice(1) # prints message global video_thread if video_thread is None or not video_thread.is_alive(): stop_event.clear() video_thread = threading.Thread(target=run_video_feed) video_thread.start() return HttpResponse("Video feed started successfully.") else: return HttpResponse("Video feed is already running.") The above code is fetching video feed while running in localhost. But when I uploaded(hosted) it in the pythonanywhere, it is not fetching the video feed and it prints Warning: unable to open video source. -
Django user permission assigning group
I have a to do list model that admin user can create,edit,and delete to do items. In the model, the team field is a dropdown list where admin can choose a team, which refers to the group containing users. How can I show items created only to the users that belongs to the team that the admin user chose? Now each user can view tasks they created/edited but I'm not sure how to let admin user to assign group(team) to allow all users in group to view the task list. models.py from django.db import models from django.contrib.auth.models import User TEAM_CHOICES = ( (' ', ' '), ('team a','TEAM A'), ('team b', 'TEAM B'), ) class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) suggestion = models.TextField(null=True, blank=True) reply = models.TextField(null=True, blank=True) team = models.CharField(max_length=200,choices=TEAM_CHOICES, default=' ') complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: order_with_respect_to = 'user' views.py class CustomLoginView(LoginView): template_name = 'item/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('tasks') class RegisterPage(FormView): template_name = 'item/register.html' form_class = UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('tasks') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) … -
Where to save this class?
Updated models.Model: class GetOrNoneManager(models.Manager): """returns none if object doesn't exist else model instance""" def get_or_none(self, **kwargs): try: return self.get(**kwargs) except ObjectDoesNotExist as e: logger.warning(e) return None class BaseModel(models.Model): class Meta: abstract = True ordering = ('-created_at',) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField('Дата создания', auto_now_add=True, db_index=True) updated_at = models.DateTimeField('Дата изменения', auto_now=True) objects = GetOrNoneManager() def str(self): return self.id.hex fffffffffffffffffffffffffffffffffffffff Is there any certain file that i should create to save code like that? -
Django using rest_framework url_pattern not mapping to model instance view
I have a Django (python) application that uses rest_framework api. I want the api to map to /api/v1/[/id]. The GET /api/v1/whs gives a page that lists the Wh objects in the database (which is MongoDB/Djongo/pymongo). Problem: GET /api/v1/whs/640444031170f24828f324bc/ does not call the def get_object(self) function (evidences by the fact the print statement never runs). The Wh document with that ObjectId exists in the MongoDB database (verified). The request gives the following webpage output: HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Below is my code This is the portion of my settings.py: INSTALLED_APPS = [ ... 'rest_framework', ... ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } This is my models.py: from django.db import models from djongo.models import fields from django.contrib.auth.models import AbstractUser from django.contrib.auth.hashers import make_password from djongo.models import fields CHARFIELD_MAX_LENGTH = 1024 # Create your models here. class AbstractModel(models.Model): _id = fields.ObjectIdField() external_id = models.CharField(max_length = CHARFIELD_MAX_LENGTH, null = True, blank = True,) options = models.JSONField(null = True, blank = True,) created_at = models.DateTimeField(auto_now_add = True, null = False, blank = False,) updated_at = models.DateTimeField(null = True, blank = True,) class Meta: … -
I want to use path value from views.py to django template html
VIEWS.PY CODE data = { "product" : { "product1":{ "path":"assets/carouselImgs/laptop1.png" }, } } I want to use this path value to load image. HTML CODE <img class="carousel-img" src="{% static 'how can i use path value here' %}" alt=""> -
Why single html <p> tag is being spilt into two <p> tags with a <br> tag between them?
Below is my template html tag ( django): <p class="card-text cfs-9 cfc-grey">{{i.post|safe|truncatechars:100}}</p> This tag render totally fine on local server, but on production server, this single <p> tag is being split into two <p> tags and an extra <br> tag appear out on nowhere between them. I think the issue is with 'truncatechars' but i could not figure out. Below is view source code from both local and production server. Local Server view page source: <p class="card-text cfs-9 cfc-grey">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the…</p> Production server view page source: <p class="card-text cfs-9 cfc-grey"><br><p>In this post I'll be demonstrating how we can deploy Django website on…</p> I tried {{i.post|truncatechars:10|safe}} instead of {{i.post|safe|truncatechars:100}} but the problem remains.Tried using 'truncatewords' but still same problem. -
Specifying a relation through multiple shared foreign keys
Let's say we have 4 models, lets call them Alpha, Beta, Gamma, and Delta and the first two are something like: class Alpha(models.Model): gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT) delta = models.ForeignKey(Delta, on_delete=models.RESTRICT) text = models.CharField(max_length=1024) class Meta: constraints = [ models.UniqueConstraint(fields=['gamma_id', 'delta_id']) ] class Beta(models.Model): gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT) delta = models.ForeignKey(Delta, on_delete=models.RESTRICT) value = models.IntegerField() As you can see the two foreign keys can be used to associate any number of rows from Beta with one row from Alpha. There is essentially a one to many relationship between Beta and Alpha. For various reasons it is not feasible to replace the two foreign keys in Beta with a foreign key to Alpha. Is there a way to define a relationship on Alpha that returns all the rows from Beta that have the same gamma_id and delta_id -
How to use aggregate functions count or length in django
would like to use the count or length function in template, but I don't know how to go about it. I would like to count the items separately of all categories models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Rock', 'Rock'), ('Pop', 'Pop'), ('Reggae', 'Reggae'), ('Disco', 'Disco'), ('Rap', 'Rap'), ('Electronic music', 'Electronic music'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) views.py A simple listing of all elements class ProductListView(View): def get(self, request): products = CD.objects.all() return render(request, 'products/statistics.html', {'products': products}) -
processing data from django form
I have a form with a drop down list: CATEGORY_CHOICES= [ ('sport', 'Sport'), ('mini', 'Mini'), ('economy', 'Economy'), ('electro', 'Electro'), ('business', 'Business'), ] class CategoryChoice(forms.Form): category= forms.CharField(label='Поиск по категории:', widget=forms.Select(choices=CATEGORY_CHOICES, ), required = False) I need that when choosing a category and pressing the "search" button, the user will be redirected to the page with the goods of the selected category? I have no idea how to link the html template, view.py and urls.py together. Could you please help me? I will be very grateful. -
Django: get most frequent objects in many to many relationship
class SoundItem(models.Model): name = models.CharField(max_length=200) class SoundCategory(models.Model): name = models.CharField(max_length=200) class SoundItemReview(models.Model): sound = models.ForeignKey(SoundItem, on_delete=models.CASCADE, related_name='sound_reviews') categories = models.ManyToManyField(SoundCategory, related_name="sound_reviews") For one instance of sound item (s), I can get its reviews with s.sound_reviews.all(), but how I count most frequent categories in its reviews (without having to manually iterate reviews and count categories)? Eg for s there are 2 reviews: review1: category1, category2 review2: category2, category3 then I want to get {"category2": 2, "category1": 1, "category3": 1} -
Passing a list of senders to the sender parameter of @receiver decorator
So at the moment, I'm working on my Django project and I have a signal receiver function that looks like this: @receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre_1') @receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre_2') @receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre_3') def task_handler_pre(sender, instance, **kwargs): # do some stuff In an attempt to make the code look cleaner, I was wondering whether would it be possible to do something like this: @receiver(pre_save, sender=[Task, TaskHistory, TaskUser], dispatch_uid='core.models.task_handler_pre') def task_handler_pre(sender, instance, **kwargs): # do some stuff i.e. Does the sender parameter accepts a list of senders as a valid argument ? If not, then does the value of the dispatch_uid parameter within the @receiver decorator, have to be different for each individual sender, or can it be the same i.e. As mentioned previously, my receiver function looks like this at the moment: @receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre_1') @receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre_2') @receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre_3') def task_handler_pre(sender, instance, **kwargs): # do some stuff What difference would it make if I make the following change: @receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre') @receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre') @receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre') def task_handler_pre(sender, instance, **kwargs): # do some stuff i.e. make the value of the dispatch_uid parameter the same ( core.models.task_handler_pre ) for each individual sender. Thanks! -
How to route nginx pages to different pages?
Hello I have django app let's suppose my site uri is example.com now i want to route my admin dashboard to another port like if users types abc.example.com it automatically routes to main page of my app but i want to have abc.example.com:445/admin/* is it possible the solution i tried was server { listen 443 ssl; server_name abc.example.com; client_max_body_size 500M; ssl_certificate /etc/nginx/my.crt; ssl_certificate_key /etc/nginx/server.key; location / { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://localhost:3001; } } server{ listen 445 ssl; server_name abc.example.com; client_max_body_size 500M; ssl_certificate /etc/nginx/my.crt; ssl_certificate_key /etc/nginx/server.key; location /admin { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://localhost:3001; } } server { listen 80; server_name abc.example.com; return 301 https://$host$request_uri; } But this itself routes to port 443 and /admin page is also available there so how to avoid this any possible solutions. -
reverse accessor model clashing Django Web App
from django.db import models from django.contrib.auth.models import AbstractUser class Customer(AbstractUser): address_line = models.CharField(max_length=255) city = models.CharField(max_length=255) postal_code = models.CharField(max_length=10) phone_number = models.CharField(max_length=20) origin_country = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='customer_profile_pics', null=True, blank=True) class Chef(AbstractUser): address_line = models.CharField(max_length=255) city = models.CharField(max_length=255) postal_code = models.CharField(max_length=10) phone_number = models.CharField(max_length=20) origin_country = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='chef_profile_pics', null=True, blank=True) class Meal(models.Model): name = models.CharField(max_length=255) description = models.TextField() picture = models.ImageField(upload_to='meal_pics') country = models.CharField(max_length=255) chef = models.ForeignKey(Chef, on_delete=models.CASCADE, related_name='meals') customers = models.ManyToManyField(Customer, blank=True, related_name='meals') class Discussion(models.Model): message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True, related_name='discussions') chef = models.ForeignKey(Chef, on_delete=models.CASCADE, null=True, blank=True, related_name='discussions') This is my models.py file I get the following error while making migrations SystemCheckError: System check identified some issues: ERRORS: meals.Chef.groups: (fields.E304) Reverse accessor for 'Chef.groups' clashes with reverse accessor for 'Customer.groups'. HINT: Add or change a related_name argument to the definition for 'Chef.groups' or 'Customer.groups'. meals.Chef.user_permissions: (fields.E304) Reverse accessor for 'Chef.user_permissions' clashes with reverse accessor for 'Customer.user_permissions'. HINT: Add or change a related_name argument to the definition for 'Chef.user_permissions' or 'Customer.user_permissions'. meals.Customer.groups: (fields.E304) Reverse accessor for 'Customer.groups' clashes with reverse accessor for 'Chef.groups'. HINT: Add or change a related_name argument to the definition for 'Customer.groups' or 'Chef.groups'. meals.Customer.user_permissions: (fields.E304) Reverse accessor … -
Django API Blog-post
models.py class CommentModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(PostModel, on_delete=models.CASCADE) comment = models.TextField() created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) Serializers.py class CommentListSerializer(serializers.ModelSerializer): class Meta: model = CommentModel fields = ['id','comment','post','user','created_at'] views.py class CommentListView(generics.GenericAPIView): permission_classes = [IsAuthenticated] queryset = CommentModel.objects.all() serializer_class = CommentListSerializer can anyone help me to retrieve all the comments that are posted under a blog post. -
i need to make more than one ime entry into the supplier model how can i do that? it only allow one ime
i have an ime model like that class Imee(models.Model): ime_number = models.CharField(max_length=256,null=False) def __str__(self): return self.ime_number def get_absolute_url(self): return reverse("ghaith:detail",kwargs={'pk':self.pk}) and i have a supplier model and i need to enter more then one ime to the supplier and more than a receipt class Supplier(models.Model): supplier_name = models.CharField(max_length=256,null=False) imee = models.ForeignKey(Imee,related_name='suppliers',on_delete=models.CASCADE) receipt_number = models.IntegerField(unique=True,null=False) receipt_date = models.CharField(max_length=256,null=False) def __str__(self): return self.supplier_name def get_absolute_url(self): return reverse("ghaith:detail",kwargs={'pk':self.pk})