Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model many to many through not working
i have mysql database that are already made. so models.py is created by manage.py inspectdb and i add artists = models.ManyToManyField(Artist, related_name='songs', through = "ArtistSong") to Song table like this. class Artist(models.Model): artist_id = models.IntegerField(primary_key=True) artist_name = models.TextField(blank=True, null=True) artist_main_genre = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'artist' class Song(models.Model): song_id = models.IntegerField(primary_key=True) issue_date = models.TextField(blank=True, null=True) album_name = models.TextField(blank=True, null=True) album_id = models.IntegerField(blank=True, null=True) song_name = models.TextField(blank=True, null=True) added_cnt = models.IntegerField(blank=True, null=True) thumb_url = models.TextField(blank=True, null=True) artists = models.ManyToManyField(Artist, related_name='songs', through = "ArtistSong") class Meta: managed = False db_table = 'song' class ArtistSong(models.Model): song = models.ForeignKey(Song, models.DO_NOTHING, blank=True, null=True) artist = models.ForeignKey(Artist, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'artist_song' i want get name and artist name of song. my views.py here. class Songs(APIView): def get(self, request, *args, **kwargs): song_list= request.GET.get('song_list') queryset = Song.objects.filter(song_id__in = song_list) rec_songs = [] for song in queryset.iterator(): #for checking print(song.song_name) print(song.artists.all()) data = { 'song_name' : song.song_name, 'artist_name': [a.artist_name for a in song.artists.all()], } rec_songs.append(data) return Response(json.dumps(rec_songs,ensure_ascii = False)) print(song.song_name) shows song_name as i intened. print(song.artists.all()) shows nothing but <QuerySet []> please help! -
Do we need to close session explicitly in django request?
Let's say, we have class class Pipe(object): def __init__(self, imp_url=IAMPORT_API_URL): requests_session = requests.Session() requests_adapters = requests.adapters.HTTPAdapter(max_retries=3) requests_session.mount('https://', requests_adapters) self.requests_session = requests_session def get(self, url, payload=None) return self.requests_session.get(url, headers=headers, params=payload) views.py class RequestAPIView(APIView): pipe = Pipe() pipe.get(...) pipe.get(...) .... After call RequestAPIView, Do we need to close self.session explicitly in pipe object? Or after RequestAPIView done, Does the self.session will be closed automatically? -
Doing inference using pytorch saved weights in .tar file using django
I am doing a machine learning project where I need to display the predictions on a webpage. The webpage is build using Django. I have predictions function and the weights of the model but how to integrate the predictions function, model, and weights in the Django code and do predictions. My prediction code def predicting(model, device, loader): model.eval() total_preds = torch.Tensor() total_labels = torch.Tensor() with torch.no_grad(): for solute_graphs, solvent_graphs, solute_lens, solvent_lens in loader: outputs, i_map = model( [solute_graphs.to(device), solvent_graphs.to(device), torch.tensor(solute_lens).to(device), torch.tensor(solvent_lens).to(device)]) print(outputs) total_preds = torch.cat((total_preds, outputs.cpu()), 0) return total_preds.numpy().flatten() I have saved the weights in .tar file so I need to run the model while loading the weights for prediction. I have no idea where to keep my PyTorch model and the weights to do inference using Django. please help. -
'dict' object has no attribute 'META' redirect error
sorry for typos, I'm using translation I want to integrate virtual pos for payment method, but the error I got is as follows Error; 'dict' object has no attribute 'META' views.py: @login_required(login_url="/user/login") def payment(request): options = { 'api_key': 'api_key', 'secret_key': 'secret_key', 'base_url': 'sandbox-api.iyzipay.com' } payment_card = { 'cardHolderName': 'John Doe', 'cardNumber': '5528790000000008', 'expireMonth': '12', 'expireYear': '2030', 'cvc': '123', 'registerCard': '0' } buyer = { 'id': 'BY789', 'name': 'John', 'surname': 'Doe', 'gsmNumber': '+905350000000', 'email': 'email@email.com', 'identityNumber': '74300864791', 'lastLoginDate': '2015-10-05 12:43:35', 'registrationDate': '2013-04-21 15:12:09', 'registrationAddress': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'ip': '85.34.78.112', 'city': 'Istanbul', 'country': 'Turkey', 'zipCode': '34732' } address = { 'contactName': 'Jane Doe', 'city': 'Istanbul', 'country': 'Turkey', 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'zipCode': '34732' } basket_items = [ { 'id': 'BI101', 'name': 'Binocular', 'category1': 'Collectibles', 'category2': 'Accessories', 'itemType': 'PHYSICAL', 'price': '0.3' }, { 'id': 'BI102', 'name': 'Game code', 'category1': 'Game', 'category2': 'Online Game Items', 'itemType': 'VIRTUAL', 'price': '0.5' }, { 'id': 'BI103', 'name': 'Usb', 'category1': 'Electronics', 'category2': 'Usb / Cable', 'itemType': 'PHYSICAL', 'price': '0.2' } ] request = { 'locale': 'tr', 'conversationId': '123456789', 'price': '1', 'paidPrice': '1.2', 'currency': 'TRY', 'installment': '1', 'basketId': 'B67832', 'paymentChannel': 'WEB', 'paymentGroup': 'PRODUCT', 'paymentCard': payment_card, 'buyer': buyer, 'shippingAddress': address, 'billingAddress': address, … -
m2m_changed signal with many-to-many through - save
I have these two basic models, class Product(models.Model): title = models.CharField(max_length=40) description = models.TextField(blank=True) price = models.DecimalField(decimal_places=2, max_digits=7, default=0) ... and class Cart(models.Model): user = models.ForeignKey( User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField( Product, blank=True, through='CartItem') total = models.DecimalField(default=0.00, max_digits=7, decimal_places=2) def recalculate_and_save(self): print("recalculate_and_save running") total = 0 for ci in self.cartitem_set.all(): total += ci.product.price*ci.quantity self.total = total self.save() , and a helper model for many-to-many relation above, to account for quantity: class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.SmallIntegerField(default=1) What I want to achieve is automatic calculation of Cart's total every time an item is added or removed. So, @receiver(m2m_changed, sender=CartItem) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): print(f"m2m_changed received; action={action}, instance={instance}") instance.recalculate_and_save() Then I realized, seeing pre_save and post_save actions in logs, that I'm likely doing something wrong - calling save in the function which is called (twice) from parent's save, as per docs. The first question is, then - why doesn't it send me into an infinite loop? And the second (and probably more important) - why am I only seeing the receiver function executing on removing items from the cart, but not on adding them? Removing is done via cart.products.remove(product_obj) , but … -
Django cant figure out how to use foreign key
''' class Project_types(models.Model): project_type = models.CharField(max_length=200) def __str__(self): return self.project_type class Projects(models.Model): project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE) project = models.CharField(max_length=200) def __str__(self): return self.project ''' When I try to run - Project_types(project_type='games').item_set.all() I get an error saying that there is no attribute item set. -
Django filter json object's list by comparing with another list
I have a model that has a field which is a JSON field. This json_field has a value which is a list. model: attr1: attr2: attr3: json_field: { jattr1: jattr2: array_field: [values ...] } I have a queryset obtained from some other filter operation: queryset I want to apply model.objects.filter() such that I obtain every instance where array_field values are present in the queryset. For example: consider 4 instances instance1: json_field: { array_field: [1, 2, 3, 4] } instance2: json_field: { array_field: [2, 4] } instance3: json_field: { array_field: [1, 4] } instance4: json_field: { array_field: [3] } and queryset is : queryset: [2, 3] I am expecting something like this: Model.objects.filter(json_field__array_field__in=queryset) # This should return instance1: json_field: { array_field: [1, 2, 3, 4] } instance2: json_field: { array_field: [2, 4] } instance4: json_field: { array_field: [3] } Thank you for your help. -
Django how to add html style in JavaScript for load more button
I successfully implement load more button but now I can't add my html style in JavaScript. This is my original style before implement load more button. see the screenshot: after implementing load more button. I have style like this. see the screenshot below: How to implement my first style for individually showing each blog. here is my JavaScript for showing html: postsBox.innerHTML += `<div class="card mb-4" style="max-width:700px";> ${post.title} <br> ${post.body} </div> ` my .html page: <div id="posts-box"></div> <div id="spinner-box" class="not-visible"> <div class="spinner-border text-primary" role="status"></div> </div> <div id="loading-box"> <button class="btn btn-primary" id="load-btn">Load more</button> </div> -
Django - Disable authenticator for Swagger
So I have a Django app with Swagger, but I also added a custom authenticator to every endpoint automatically with REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'cheers.utils.authenticator.CognitoAuthentication', ), } How do I turn this off for swagger? The reason I'm not sure is because Swagger is added to URLs it's not a view How do I disable automatic authentication for swagger? Also I guess a side question would be how to disable this URL when debug is False -
Django dict(request.POST.lists()) returns twice(normal, empty)
Views.py @login_required(login_url="/users/login") def tresults(request): ids = dict(request.POST.lists()) print(ids) data = ids['selected'] msg = data.pop(0) HTML <form id = "{{ msg }}" action="tresults" method="POST"> <input type="hidden" name="selected" value="{{ msg }}"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>GuildName</th> <th>GuildID</th> <th>Check</th> </tr> </thead> <tbody> {% for guild in guilds %} <tr> <td>{{ guild.name }}</td> <td>{{ guild.id }}</td> <td> {% csrf_token %} <input type="checkbox" name="selected" value="{{ guild.id }}"/> </td> </tr> {% endfor %} </tbody> </table> </div> </form> <a class="dropdown-item" href="#" onclick="document.forms['{{ msg }}'].submit();">Send</a> and I getting from print(ids) {'selected': ['61660a3afe554cfd1b4fe98f', '880716169986859039'], 'dataTable_length': ['10'], 'csrfmiddlewaretoken': ['OE9lhwbkU1KlKrDHiip1G6Yd5i9oOPS1bA0s2DapHY6RDbXc7UHc4KPd5jOlCLNm']} [13/Oct/2021 07:55:57] "POST /posts/post/tresults HTTP/1.1" 302 0 {} Internal Server Error: /posts/post/tresults I tried with various way like request.POST.dict() <- returns with only one value request.POST.copy() and dict(ids.iterlists()) or dict(ids) <- not working I don't know why two dict printed and last one is empty. I want to fix this -
Celery - What pool should I use for windows heavy cpu process and redis backend for status tracking?
I am running python 3.9, Windows 10, celery 4.3, redis as the backend, and aws sqs as the broker (I wasn't intending on using the backend, but it became more and more apparent to me that due to the library's restrictions on windows that'd I'd be better off using it if I could get it to work, otherwise I would've just used redis as the broker and backend). To give you some context, I have a webpage that a user interacts with to allow them to do a resource intensive task. If the user has a task running and decides to resend the task, I need it to kill the task, and use the new information sent by the user to create the new task. The problem for me arrives after this line of thinking: Me: "Hmmm, the prefork pool is used for heavy cpu background tasks... I want to use that..." Me: Goes and configures settings.py, updates the celery library, sets the environment variable to allow windows to run prefork pool - os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1'), sets a few other configuration settings, etc, runs the worker and it works. Me: "Hey, hey. It works... Oh, I still can't revoke a task … -
How to do predictions in django using restframe work
I am doing a machine learning project where I need to display the predictions on a webpage. The webpage is build using Django. I have predictions function and the weights of the model but how to integrate the predictions function, model, and weights in the Django code and do predictions. -
Celery task name is different in two workers
I have the following directory structure for a celery project: my_app ├── __init__.py ├── my_tasks.py I run the worker with exactly the same command celery -A my_app.my_tasks.post_request worker -l DEBUG in 2 nodes but got two different task names, one is absolute path: [tasks] . celery.accumulate . celery.backend_cleanup . celery.xxx . ... . my_app.my_tasks.post_request The other one is more like a relative path: [tasks] . celery.accumulate . celery.backend_cleanup . celery.xxx . ... . post_request How does celery generate the name of the task? I have read the section names of the official documentation but am still not able to find why the names are different in the two workers. -
Django why getting this error unsupported operand type(s) for -: 'NoneType' and 'int'
I am trying to implement load more button so I am writing this view for load json data but I am not understanding why I am getting this error. unsupported operand type(s) for -: 'NoneType' and 'int' here is my view: class PostJsonListView(View): def get(self, *args, **kwargs): print(kwargs) upper = kwargs.get('num_posts') lower = upper - 3 posts = list(Blog.objects.values()[lower:upper]) posts_size = len(Blog.objects.all()) max_size = True if upper >= posts_size else False return JsonResponse({'data': posts, 'max': max_size}, safe=False) -
Factoryboy can not generate database-dependent field
I use django-cities-light to store the user locations. However I need to import a huge dataset of countries & cities to the database. How can I create a factory that would automatically populate these fields during the tests? When not testing, the factory works properly by Country.objects.all(). But when testing, the database is empty and can not find any countries: IndexError: Cannot choose from an empty sequence. What should be the right approach for such cases? If you have a better solution to the use of LazyAttributes below, let me know the better approach. class UserProfileFactory(DjangoModelFactory): class Meta: model = UserProfile # ... birth_country = FuzzyChoice(Country.objects.all()) or None birth_region = factory.LazyAttribute( lambda o: o.birth_country.region_set.order_by("?").first() ) birth_subregion = factory.LazyAttribute( lambda o: o.birth_region.subregion_set.order_by("?").first() ) birth_city = factory.LazyAttribute( lambda o: o.birth_region.city_set.order_by("?").first() ) -
Django - How to filter and return data by groups
I have a model which I want to return group by an attribute of the object itself. Let's suppose the model is the next one: class User(): username = models.CharField(max_length=50, unique=True) group = models.CharField(max_length=20) Later in the view, I would be getting by group all the users: group1 = User.objects.filter(group='1') group2 = User.objects.filter(group='2') group3 = User.objects.filter(group='3') But that would return for each group the next structure: [{"username":"user1", "group":"1"}] [{"username":"user2", "group":"2"}] [{"username":"user3", "group":"3"}] How can I obtain the next structure (where the group is the root) directly from the filter or how can I combine the groups to achieve that: [ "1": [{"username":"user1","group":"1"}], "2": [{"username":"user2","group":"2"}], "3": [{"username":"user3","group":"3"}] ] -
upload image from next.js to django to store in aws s3
I set up functionality for s3, I can easily upload images from Django admin interface. I have "createProduct" page and I want to create a product by sending form data from next.js. Django stores the URL s3 bucket in DB and retrieves the image from s3 when needed. I set view image and cropping it functionality and it works as well. For this I have a separate component: <div className="form-group"> <label htmlFor="image">Image</label> <FileLoader onFileUpload={image => setValue('image', image._id)} /> </div> I need to create an endpoint. Admin, first uploads the image, image gets saved to s3, then admin gets the url of the image, and passes it to the form data, so form data will be sent to the createProduct endpoint. @api_view(['POST']) @permission_classes([IsAdminUser]) def createProduct(request): user=request.user print("user in post",user) print("request.data",request.data) name=request.data['name'] price=request.data['price'] brand=request.data['brand'] countInStock=request.data['countInStock'] category=request.data['category'] description=request.data['description'] // Here i need to send the imag url I guess image=request.FILES.get('image') print("image",image) product=Product.objects.create(user=user, name=name, price=price,brand=brand, countInStock=countInStock,category=category,description=description, image=image) product.save() serializer=ProductSerializer(product, many=False) return Response(serializer.data) -
Django Custom User Model and SuperUser
I am trying to create an app which a web3 user can use their wallet to sign in BUT I want the superuser to still use a username/password. (my future plan is to create a custom backend to do the web3 auth flow) I was close with this as I was able to create a first admin that could use the username/password but realized it was failing on the next createsuperuser with this: django.db.utils.IntegrityError: UNIQUE constraint failed: users_web3user.public_address So I tried for now just adding a random integer to satisfy that just to see if it would work but the same issue constantly shows up. Would this be the proper way to go about this and to seperate my users from my superusers? Also, my debugger is never called even though I have set in my settings.py where user is my app: AUTH_USER_MODEL = 'users.Web3User' models.py: class Web3UserManager(BaseUserManager): def create_user(self, public_address): if not public_address: raise ValueError('Users must have a public_address') user = self.model( public_address=public_address, nonce=secrets.token_urlsafe(32) ) user.save(using=self._db) return user def create_superuser(self, username, password=None): import ipdb; ipdb.sset_trace() public_address=secrets.randbelow(299) print(public_address) user = self.create_user( username=username, password=password, public_address=public_address ) user.is_admin = True user.save(using=self._db) return user class Web3User(AbstractUser): public_address = models.CharField(max_length=64, unique=True) nonce = models.CharField(max_length=64) -
graphene code run before django data migrations
I wrote a piece of code that generates graphene input object type dynamically from the database. when I try to run ./manage.py migrate that code runs before the migration and caused django.db.utils.ProgrammingError I have the same issue in run the Pytest too. how can I prevent this code from running before the data migrations -
django - I can't use the Q filter model with 2 related databases
I have the 2 following models related with 2 different databases at models.py: class AnalogicalValues(models.Model): id = models.BigAutoField(primary_key=True) date = models.DateField() description = models.ForeignKey(ExpensesDescription, models.DO_NOTHING) continent_id = models.ForeignKey( 'WorldContinent', db_column='continent_id', on_delete=models.DO_NOTHING ) (...)hide code(...) city_id = models.ForeignKey( 'WorldCity', db_column='city_id', verbose_name='City', on_delete=models.DO_NOTHING ) value = models.FloatField() comments = models.CharField(max_length=255, blank=True, null=True) user_id = models.ForeignKey(User, db_column='user_id', on_delete=models.DO_NOTHING) class Meta: managed = False db_table = 'analogical_values' ordering = ('-date', '-id') class WorldCity(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=255, verbose_name='City') continent = models.ForeignKey(WorldContinent, models.DO_NOTHING) country = models.ForeignKey(WorldCountry, models.DO_NOTHING) subcountry = models.ForeignKey(WorldSubcountry, models.DO_NOTHING) last_update_db = models.DateTimeField() class Meta: managed = False db_table = 'cities' ordering = ('name',) verbose_name_plural = 'List of World Cities' verbose_name = 'World City' def __str__(self): return self.name The relationship between them are city_id from AnalogicalValues and id from WorldCity and each model is mapped of respective database at routers.py. The description field on AnalogicalValues is a foreignkey of other table in same database as analogical_values and it's working fine. class WorldRouter: route_app_labels = {'myapp'} route_model_list = {'WorldCity'} def db_for_read(self, model, **hints): if ( model._meta.app_label in self.route_app_labels and model._meta.object_name in self.route_model_list ): return 'world_db' return None def db_for_write(self, model, **hints): if ( model._meta.app_label in self.route_app_labels and model._meta.object_name in self.route_model_list ): return … -
Number of Items per month works in CreateView, but not in TemplateView
My goal: get Count of items per month displayed in my template, i.e.: May 2021 - 5, June 2021 - 10, Sep 2021 - 3, Oct 2021 - 2, etc What I've done. I first created a test-project and my Index view inherited from CreateView (needed that for a form). Everything worked fine. However, in my main project my IndexView is inherited from django's TemplateView, and with the same code it shows like this: Sep 2021 - 1, Sep 2021 - 1, Oct 2021 - 1, Oct 2021 - 1, Oct 2021 - 1... you get the point. So, for some reason, it sees every item as a separate date without trying to aggregate them. So the difference-maker has to be the inheritance from different views in django, however, in my main project, I cannot make my index view inherit from CreateView. Also, I'm still new to Django and would really appreciate all the help I can get. It took me a lot of effort to figure it out up until this point. Here's my working code (in the test-project): models.py class Movie(models.Model): title = models.CharField('Movie name', max_length=100) gross = models.IntegerField('Gross', help_text='Worldwide, in dollars.') release_date = models.DateField('Date of release', blank=True, … -
Subprocess in views.py django app didn't work?
I'm trying to call a script in views.py like this from subprocess import Popen p1 = Popen('python3 {}'.format(path), shell=True, stdout=PIPE, stderr=PIPE) answer = p1.communicate(timeout=5) print('answer', answer) And i have result answer (b'', b'') but when i call from terminal python3 /tmp/tmp9nqnbve3 i get correct output and even if I call the same code from outside of django, I also get the correct result -
userpost() got an unexpected keyword argument 'instance'
I am practicing a little CRUD project in django. here is the views.py of crudproject from django.contrib import messages from django.shortcuts import get_object_or_404, redirect, render from .models import userpost from .forms import customerform #creating postdate def create(request): form= customerform() if request.method=='POST': Form=customerform(request.POST) if Form.is_valid(): Form.save() Form={} context ={'form':form} return render(request,'create.html',context) #reading the post def read(request): user_data=userpost.objects.all() context ={ 'user_data':user_data} return render(request,'read.html',context) #Updating the post def update(request,pk): get_user_data=get_object_or_404(userpost,pk=pk) form= userpost(instance=get_user_data) if request.method=='POST': form=userpost(request.POST,isinstance=get_user_data) if form.is_valid(): form.save() messages.success(request,'User data has been Updated') return redirect('read') context={'form':form} return render(request,'update.html',context) #deleting the post def delete(request,pk): get_user=get_object_or_404(userpost,pk=pk) get_user.delete() messages.error(request,'User deleted') return redirect('/') urls.py of crud project from django.urls import path from .import views urlpatterns = [ path('new/',views.create,name='create'), path('update<int:pk>/',views.update,name='update'), path('delete/<int:pk>/',views.delete,name='delete'), path('',views.read,name='read') ] but the server says TypeError at /update8/ userpost() got an unexpected keyword argument 'instance' Request Method: GET Request URL: http://localhost:8000/update8/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: userpost() got an unexpected keyword argument 'instance' Exception Location: C:\Users\ITS\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py, line 503, in __init__ please help me to figure this out.it would be so much helpful if you give me a little explaination. Thanks in advance -
TypeError: argument of type 'PosixPath' is not iterable, old solution didn't worked
I am learning django and I'm getting this error and even when I go to admin the CSS is also not loading. the things I have added on models.py are also not showing on admin. Please Some one help me to get out of this problem. I tried searching google and youtube. Error `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 "/Users/subas/opt/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/subas/opt/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/subas/opt/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/Users/subas/opt/anaconda3/lib/python3.8/site-packages/django/db/utils.py", line 224, in close_all connection.close() File "/Users/subas/opt/anaconda3/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 248, in close if not self.is_in_memory_db(): File "/Users/subas/opt/anaconda3/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/Users/subas/opt/anaconda3/lib/python3.8/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable` Model.py from django.db import models class Category(models.Model): name = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: verbose_name_plural = 'categories' def get_absolute_url(self): return reverse('store:category-list', args=[self.slug]) def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Product_creator') title = models.CharField(max_length= 255) brand = models.CharField(max_length=255, default='Non-branded') description = models.TextField(blank=True) image = models.ImageField(upload_to='images/') slug = models.SlugField(max_length = 255) price … -
django Google maps ipa
I'm creating a website with django frame work. and I want when a user order something a little frime shows up and the user can enter the delivery address within the map in the frame How can I do that ? ?