Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-oscar How does the download work? for digital product
guys, I started an all e-shop for digital products using django-oscar reading the documentation, it states that support for digital products is available. but I haven't figured it out yet. I will be grateful for any help. -
Reverse for 'ptrips' with arguments '('', '')' not found. 1 pattern(s) tried: ['details/trips/(?P<trip_id>[0-9]+)/(?P<passenger_id>[0-9]+)/$']
This is a train tickets booking system, im trying to pass 2 id(trip_id/passenger_id) at the same url path so the django can remember the number of passengers and then create a number of tickets forms based on the number of passenger by id urls.py path('trips/<int:trip_id>/',views.ticket_booking, name='trips'), path('trips/<int:trip_id>/<int:passenger_id>/',views.passengers_page, name='ptrips'), path('review/<int:ticket_id>/',views.review_page, name='rtickets'), re_path(r'^from/(?P<start_station>[0-9]{1,50})/$', views.details_page, name='details_page'), path('', views.details_page, name='booking'), views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.core.exceptions import ValidationError from .models import Ticket, Trip, Passenger from django.http import Http404 from django.shortcuts import get_object_or_404 def ticket_booking(request, trip_id, passenger_id): trip = get_object_or_404( Trip, pk=trip_id) passengers = list(Passenger.objects.filter(pk=passenger_id)) error = None ticket = None if request.method == 'POST': first_name = request.POST.get('first_name') middle_name = request.POST.get('middle_name') last_name = request.POST.get('last_name') email = request.POST.get('email') gender = request.POST.get('gender') ticket = Ticket(trip=trip,first_name=first_name, middle_name=middle_name, last_name=last_name, email=email,gender=gender) try: ticket.full_clean() ticket.save() return redirect('tickets',ticket_id=ticket.id) except ValidationError as e: error = dict(e) print(e) context = { 'trip': trip,'error':error, 'ticket':ticket, 'passengers':passengers } return render(request, 'details/ticket.html', context) html <div class="container marketing"> {% for trip in trips %} <div class="card text-center "> <div class="card-header"> Ride Details </div> <div class="card-body"> <h4>Start</h4> <h5 value="{{trip.id}}">{{trip.start_station}}</h5> <h4>End</h4> <h5 value="{{trip.id}}">{{trip.end_station}}</h5> <a class="btn btn-primary" href="{% url 'ptrips' trip_id passenger.id %}" role="button">Book Now</a> </div> </div> {% endfor %} </div> -
How to create a GROUP of users with it MANAGER able to perform an ACTION in DJANGO 2.1
How can I implement the feature for a user in the web app to create a specific “group” then become sort of the manager of that group with the ability to accept people, delete users who belong to that group. Other users can request access to that group. Each group created has the ability to perform an action. I am looking for the best the approach to build this feature. -
How to cancel Stripe subscription in Django?
This does not work. I'm trying to cancel a user's subscription. user = request.user # here this pulls the customer customer = stripe.Customer.retrieve(user.stripe_customer_id) # this fails stripe.Subscription.delete(customer['subscription']) -
How to build json like this
I want to build json something like this { "meta":[ { "key1": 12345, "key2": "berlin", "key3": "best place", "key4": 58 }, { "key1": 6789, "key2": "bangldesh", "key3": "great place", "key4": 58 } ] } I am getting data for that in a list called mylist. mylist may have n size <class 'list'>: [('berlin', 12345, 'best place', 58), ('bangldesh', 6789, 'great place', 58)] I also have keys variable as keylist. keylist may con be of n size <class 'list'>: [('key1',), ('key2',), ('key3',), ('key4',)] I tried to build json as count = 0 for i in range(0,maxLen): key = keylist[count][0] value = mylist[0][count] data[key] = value print(data) count = count + 1 jsonResult = json.dumps(data) I am getting name error -
django-tables2 reverse access foreign attributes from through table
I have got 3 tables of Truck, Waybills, and Switch. The Switch table is a through table that is the product of a many-to-many recursive relationship of the Truck with itself. I am using a tables2-table to display the data. The problem is that I was not able to display attributes from the Waybill table in reverse from either the Truck or the Switch table. Here are the models showing @property function that I used unsuccessfully for the reverse: class Waybill(models.Model): waybill_id = models.AutoField(primary_key=True, verbose_name = 'Waybill ID') truck_no = models.ForeignKey(Truck, on_delete=models.CASCADE, to_field='truck_no', related_name='waybills', verbose_name='Truck Registration No') vis_waybill_no = models.PositiveIntegerField(default=1, unique=True, db_index=True, null=True, blank=True, verbose_name='Vision Waybill No') man_waybill_no = models.CharField(max_length=75, unique=True, default='null', null=True, blank=True, db_index=True, verbose_name='Manual Waybill No') organization = models.CharField(max_length=75, null=True, blank=True, default="UNICEF", verbose_name='Organization') destination = models.CharField(max_length=75, null=False, default="Bentiu", verbose_name='Destination') class Truck(models.Model): truck_id = models.AutoField(primary_key=True, verbose_name='Truck ID') truck_no = models.CharField(max_length=14, unique=True, db_index=True, null=False, verbose_name='Truck Plate No') trailer_no = models.OneToOneField(Trailer, on_delete=models.CASCADE, unique=False, null=True, to_field='trailer_no', related_name='trucks', verbose_name='Trailer No') make = models.CharField(max_length=14, null=True, verbose_name='Make') switches = models.ManyToManyField('self', through='Switch', symmetrical=False, related_name='switched_to') def __str__(self): return u'%s' % self.truck_no+" / "+self.trailer_no.trailer_no @property def get_organization(self): waybills = self.waybill_set.all() print(x.truck_no for x in waybills) organization = waybills.objects.filter(truck__pk=1) return organization class Switch(models.Model): from_truck = models.ForeignKey(Truck, on_delete=models.CASCADE, related_name='from_trucks') credit_truck … -
how to iterate other fields when using group-by or values() in django(how to get data of other fields in the same instance)
how to get other fields when i use values() or group by in django i want to get other fields data in the same model (instance) class Product(models.Model): product_name = models.CharField(unique=True, max_length=50) pass def __str__(self): return self.product_name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') pass def __str__(self): return str(self.products.all()) class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) pass def __str__(self): return str(self.product) views.py class Lists(ListView): template_name = 'show.html' context_object_name = 'productss' def get_queryset(self): return ProductOrder.objects.filter(ordering__active=True).values( 'product').annotate( quantity_total=Sum(F('quantity'))) {% for product in productss %} <tr class=""> <td style="text-align: center;">{{ product.product }}</td> {% endfor %} and also tried this <td>{{ product.product.product_name }}</td> is there a way to achieve this goal? thanks for any advice ! -
How to get the HTTP request of python -m x.wsgi?
In my Server, I use SCREEN -d -m python3 -m Qn02.wsgi running my project, I can see by ps -ef | grep python3 root 2285 1 0 20:42 ? 00:00:00 SCREEN -d -m python3 -m Qn02.wsgi but I have a question, that's how to see the requests from client? Use the python3 -m x.wsgi, how to get the HTTP request log? or current HTTP request? -
Django select_for_update function in concurrent process
When I testing the function of update_or_create in multi threading condition, I found the result is not what I wanted,they created more than one record in MySQL. As the code show, update_or_create used select .. for update to lock rows in MySQL, then it should be only one record in MySQL. I used SQLAlchemy and row sql has proved that. So, is the Django codes wrong? with Django code: def get_or_create_ins(): p, created = OxalicAcid.objects.update_or_create(defaults={"formula": "20", "degree": "80"}, name="smart") def run(): for i in range(10): t = threading.Thread(target=get_or_create_ins, args=()) t.start() if __name__ == "__main__": # more than one record will be created run() with SQLAlchemy code: @contextmanager def transaction_atomic(): session = Session() try: yield session session.commit() except Exception as e: session.rollback() raise e def get_result_with_update(session, name): sql = text(""" select * from acid_oxalicacid where name = :name for update """) params = dict(name=name) cursor = session.execute(sql, params) result = cursor.fetchall() return result def get_result(session, name): sql = text(""" select * from acid_oxalicacid where name = :name """) params = dict(name=name) cursor = session.execute(sql, params) result = cursor.fetchall() return result def create_data(session, name, degree, formula): sql = text(""" insert into acid_oxalicacid (name, degree, formula) values (:name, :degree, :formula) """) params = … -
DRF: AttributeError: type object 'Plan' has no attribute 'get_extra_actions'
I an creating a rest API where I want to have a url with a query parameter like this: http://127.0.0.1:8000/API/prices?portion=small To do this I am folliwing the official docs: "Filtering against query Parameter" This is my view: class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): queryset = Purchase.objects.all() portion = self.request.query_params.get('portion', None) if username is not None: if portion == "small": queryset = queryset.filter(portion=False) elif portion == "large": queryset = queryset.filter(portion=True) return queryset In my urls.py I am creating a router and registering this view like below: router = routers.DefaultRouter() router.register(r'prices', views.PurchaseList, base_name='subprices') urlpatterns = [ path('API/', include(router.urls)), ... ] However, this is producing the below error on runserver: AttributeError: type object 'PurchaseList' has no attribute 'get_extra_actions' I have already managed to make the api work without any query following their docs again. How can I solve this. im certinely doing something wrong either in the router.register() or in the view -
How to specify a list of values in a form in which CheckboxSelectMultiple is used?
I have a problem with the form in django. It uses the CheckboxSelectMultiple widget, but I need to set a list of possible choices only for posts created by the currently logged in user. Any idea? form: class CycleForm(BSModalForm): class Meta: model = Cycle fields = ['title', 'description', 'posts'] widgets = { 'posts': forms.CheckboxSelectMultiple(), } models class Cycle(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) posts = models.ManyToManyField(Post) def __str__(self): return self.title -
How to add comments form to frontend in Django?
I wanna add comments form to my Django project. I've added successfully my Comments app to Django admin panel and everything works well in the admin panel. I don't know how to show the comments form on the frontend and that form to be usable by the users. models.py class Comment(models.Model): post= models.ForeignKey(Tellmeyourstory, on_delete=models.CASCADE, related_name='comments') user2 = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) views.py def detail(request,stories_id): stories=get_object_or_404(Tellmeyourstory, pk=stories_id) return render(request, 'detail.html', {'stories': stories}) -
Append value to Django model
I have 2 DB Models: class Book(models.Model): title = models.CharField(max_length=150, null=False) author = models.CharField(max_length=150, null=False) date_pub = models.DateField(verbose_name="Date Published") and class Customer(models.Model): name = models.CharField(max_length=25, null=False) surname = models.CharField(max_length=35, null=False) age = models.IntegerField(null=False) book = models.ForeignKey(to=Book, on_delete=models.CASCADE) My app was created recently, so i use manage.py shell to insert data to these models. For example, let's say I created books with title "Kolobok" and "Zolotaya Ribka". Next, I created customer "Vasya". When I created customer "Vasya", I pointed field book as "Kolobok". But over time, i want to append book "Zolotaya Ribka" to "Vasya" 's books. How i can to that? -
how to submit dynamic table to with html post
I have a html table which basically derived from my django model <form action="{% url 'checkout' %}" method="POST"> <table id="table" class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Item</th> <th scope="col">Quntity</th> <th scope="col">Price</th> </tr> </thead> <tbody> {% csrf_token %} {% for item in cartitems %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ item.name }}</td> <td data-count="1" id="counter_{{ forloop.counter }}"> <button onclick="minus({{ forloop.counter }})" id="minusButton" data-count="1" class="btn btn-default btn-xs"> <i class="fas fa-minus mr-2"></i> </button> 1 <button onclick="plus({{ forloop.counter }})" id="plusButton" data-count="1" class="btn btn-default btn-xs"> <i class="fas fa-plus ml-2"></i> </button> </td> <td data-price="{{ item.price }}" id="counter_{{ forloop.counter }}"> {{ item.price }} </td> </tr> {% endfor %} </tbody> <tfoot> <tr> <td>Total Price</td> <td></td> <td></td> <td id='totalPrice'></td> </tr> </tfoot> </table> </div> <div> <button type="submit" class="btn btn-default btn-lg">Proceed To Checkout</button> </div> </form> my quantity field in table comes from user so I want to post all data from table to django, Pls let me know if there is any easy way to do that. right now my form doesnt do anything. I know you can post quatity field through ajax but I do not want that because user might also remove some of the items from the cart -
How to disable a button after clicking it and enable it after the login process is completed by checking the server response in django
I am working on a registration functionality in Django, python. When I click the Register button, the button should disable and after successful registration, it should enable again automatically. How to achieve this. Please help. Thank you. I tried using ajax, but I don't know how to check the response from the server, whether the user is registered successfully or not. -
ModuleNotFoundError in gunicorn start
My Django project has this directory structure: . ├── gnjp │ ├── gnjp │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── app1 │ ├── app2 │ ├── manage.py │ └── templates ├── bin ├── include ├── lib using a virtual environment and works fine with python manage.py run server using some pip-installed modules like django-bootstrap4, django-bootstrap-datepicker-plus. From the higher-level gnjp-directory I do gunicorn gnjp.wsgi and get this error: [2019-09-07 14:20:28 +0200] [72408] [INFO] Starting gunicorn 19.9.0 [2019-09-07 14:20:28 +0200] [72408] [INFO] Listening at: http://127.0.0.1:8000 (72408) [2019-09-07 14:20:28 +0200] [72408] [INFO] Using worker: sync [2019-09-07 14:20:28 +0200] [72411] [INFO] Booting worker with pid: 72411 [2019-09-07 14:20:28 +0200] [72411] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/..../gnjp/gnjp/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup … -
How to create this type of json
I have a tuple like mytuple = ('somevalue', 99999, 'jjj', 99) from this tuple I want to make json like { "key1":'somevalue', "key2":'99999, "key3":'jjj', "key4":99 } the number of keys are not constant they can change and also value and number of keys are equal to number of objects I tried as data = {} for i in range(0,maxLen): key = keydata[0][i] value = valuedata[0][i] data[key] = data[value] I am getting key error while creating json -
How do I prevent post_save signals from triggering from a nested foreign key field?
Django model is sending two post_save signals and I can't figure out how to handle them. I want to trigger a single post_save signal on the save of an instance that has a foreign key field that is also being saved at the same time. This solution: How to save a model without sending a signal? seems close to home but my foreign key field must be an entirely new instance which means the update method won't work. Here's my model event = Event( start_date=template_fields['start_date'], end_date=template_fields['end_date'], event_title=f'Stock Count Reminder', description=f'Stock reminder count on auto scheduling', event_type=template_fields['event_type'] ) event.save() stock_tempalate.schedule_time = event stock_tempalate.created_by = info.context.user stock_tempalate.unique = True stock_tempalate.save() I want only stock_template.save() to trigger the post_save signal and not event.save() Here is my signal: @receiver(post_save, sender=StockCountTemplate) def start_job(sender, instance, **kwargs): if 'created' in kwargs: if not kwargs['created'] and instance.unique: start_schedule_templates() Putting a debugger in the signal's callback shows that I am receiving two signals. The first one doesn't have field values for the stock_templates while the second one does. Doing a print(kwargs) inside the callback prints the following: The first trigger: {'signal': <django.db.models.signals.ModelSignal object at 0x10d00fc50>, 'created': True, 'update_fields': None, 'raw': False, 'using': 'default'} [] And the second trigger which … -
ModuleNotFoundError: No module named 'posts' in Django
when i run python manage.py makemigrations,no module error found occur, plz help me settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts' ] urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from posts.views import index, blog, post urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog), path('post/', post), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) post> models.py from django.db import models from django.contrib.auth import get_user_model # Create your models here. User =get_user_model() class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) comment_count = models.IntegerField(default = 0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) def __str__(self): return self.title (env) C:\Users\Dell\project4\src>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Dell\Envs\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Dell\Envs\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Dell\Envs\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Dell\Envs\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Dell\Envs\env\lib\site-packages\django\apps\config.py", line 90, in create module … -
TypeError at /filter Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'
my project in weather data is fetch by data base in django framework after that data is convert daily to weekly that web page in error is TypeError at /filter Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index' '''django view html in fetch `def filter(request): date_min = request.POST.get('date_min','') date_max = request.POST.get('date_max','') qs = weather_data.pdobjects.filter(DATE__range=(date_min,date_max)) df = qs.to_dataframe(fieldnames=['id','DATE','ET','EP','BSS','RF','WD','WD1','WS','DT1','WT1','DT2','WT2','MAXT','MINT','RH11','RH22','VP11','VP11','CLOUDM','CLOUDE','SOIL1','SOIL2','SOIL3','SOIL4','SOIL5','SOIL6','MinTtest','MaxTtest1','MaxTtest2'],index='id') df = df.resample('W').agg({'ET':'sum','EP':'sum','BSS':'sum','RF':'sum','WD':'sum','WD1':'sum','WS':'sum','DT1':'sum','WT1':'sum','DT2':'sum','WT2':'sum','MAXT':'sum','MINT':'sum','RH11':'sum','RH22':'sum','VP11':'sum','VP11':'sum','CLOUDM':'sum','CLOUDE':'sum','SOIL1':'sum','SOIL2':'sum','SOIL3':'sum','SOIL4':'sum','SOIL5':'sum','SOIL6':'sum','MinTtest':'sum','MaxTtest1':'sum','MaxTtest2':'sum'},loffset = pd.offsets.timedelta(days=-6)) return render(request,"reports.html",locals()) ''' {% for data in df %} <td>{{data.ET}}</td> <td>{{data.EP}}</td> {% endfor %} ''' -
Render text from a dictionary/query in Django
When I render my queryset onto my Django template it renders the whole queryset with the curly brackets.Image below I just need value of the dictionary not the key. I'm not sure if it's printing it because the whole queryset is a string. this is my context in my view, I am joining 2 sentences into a list and then trying to render them to the template eng_sentance_flash = model.objects.filter(show_sentance = True).values('sentance_eng')[:1] #limit 1 esp_sentance_flash = model.objects.filter(show_sentance = True).values('sentance_esp')[:1] zip_flash_sentances = list(zip(eng_sentance_flash,esp_sentance_flash)) return render(request, template_name, {'sentances_list': user_sentances,'zip_flash_sentances':zip_flash_sentances}) And here is the code where I am trying to print it to the screen {% for rand in zip_flash_sentances %} <p>{{ rand.0 |safe }}</p> <p>{{ rand.1 |safe }}</p> {% endfor %} And the output looks like this on the screen {'sentance_eng': 'Croagh Patrick is the sacred mountain of Ireland, where St. Patrick is supposed to fast for 44 days when he came to Christianize Ireland in the 5th century'} {'sentance_esp': 'Croagh Patrick es la montaña sagrada de Irlanda, donde se supone que San Patricio ayunó durante 44 días cuando vino a cristianizar Irlanda en el siglo V'} -
TypeError when I run collectatic to save the static in S3 bucket using django
I'm a bit new to django and I'm trying to run collectstatic from the terminal (python manage.py collectstatic) in order to collect the static files in the S3 bucket but I getting the following error: $ python manage.py collectstatic C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\storages\backends\s3boto3.py:282: UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL. "The default behavior of S3Boto3Storage is insecure and will change " You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\core\management__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 199, in … -
how to display foreign key values instead of its ID
how to display foreign key value instead of its ID models.py class Product(models.Model): product_name = models.CharField(unique=True, max_length=50) pass def __str__(self): return self.product_name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') pass def __str__(self): return str(self.products.all()) class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) pass def __str__(self): return str(self.product) my views.py class ListOfOrder(ListView): template_name = 'order/product_group.html' context_object_name = 'productss' def get_queryset(self): return ProductOrder.objects.all() show.html {% for product in productss %} <tr class=""> <td style="text-align: center;">{{ product.product }}</td> {% endfor %} and also tried this <td style="text-align: center;">{{ product.product.product_name }}</td> is there a way to achieve this goal? thanks for any advice ! -
NoReverseMatch for user profile view
I need two different views for the user: a view user_details, it show the details of model User; a view user_profile, it show the details of model UserProfile models.py from django.contrib.auth.models import User from django.db import models from django.urls import reverse class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile_user', ) many_other_fields.... views.py from django.contrib.auth.models import User from django.shortcuts import get_object_or_404, HttpResponseRedirect, redirect, render from .models import UserProfile def user_details(request, username): user_details = get_object_or_404(User, username=username) template = 'usermanager/reading/user_details.html' context = { 'user': user_details, } return render(request, template, context) def user_profile(request, username): profile = get_object_or_404(UserProfile, username=profile_user.username) template = 'usermanager/reading/user_profile.html' context = { 'user_profile': profile, } return render(request, template, context) urls.py path('account-manager/<username>/', views.user_details, name="user_details"), path('account-manager/<username>/profile/', views.user_profile, name="user_profile"), template.html <a href="{% url 'user_details' username=user.username %}">User Details</a> <a href="{% url 'user_profile' username=userprofile.profile_user.username %}">User Profile</a> With this approach I see the error below: NoReverseMatch at /account-manager/max/ Reverse for 'user_profile' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['account\-manager\/(?P[^/]+)\/profile\/$'] How I can solve this problem? Can you suggest me another approach? -
Django, is it mandatory to have USERNAME_FIELD?
One type of user authenticate with phone number Another type of user authenticate with email. So some users don't have phone, and some don't have email. Can I specify USERNAME_FIELD to be id ? or don't have it at all?