Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mocking a function that behaves as if exception never occurred
I am have django view that calls the function on post request, and that function internally calls an other external API, which required to keys to connect. In case of failure that exception occur. What I want is to behave this method behave as if everything is fine, and no exception occurred. But I am not able to do so. What I have tried so far: This is my view @action(detail=False, methods=["POST"]) def unsubscribe(self, request, *args, **kwargs): subscription_id = request.data.get('email') if subscription.email: remove_email_from_list(subscription.email) return Response("Success") this is my remove_email_from_list remove_email_from_list(email): result = exteral_api(email) if result != "1": raise SendyError(result) My test: @mock.patch('core.utils.sendy.remove_email_from_list') @mock.patch('core.utils.simple_texting.remove_phone_from_list') @mock.patch('requests.post',"API.external_api") def test_unsubscribe(self, mock_remove_email, mock_remove_phone, mock_post, mock_external_api): mock_external_api.side_effect = None mock_remove_email.return_value = mock.MagicMock() mock_remove_phone.return_value = mock.MagicMock() mock_post.return_value = mock.MagicMock() self.login_admin() url = reverse('v2-subscription-list') url = f"{url}unsubscribe/" response = self.client.post(url, data={'email': "randomperson@internet.com"}) self.assertOK(response) self.assertEqual(Subscription.objects.all().count(), 0) When I do this it actually access the internet and try the API, but when that API fails I get this error sendy.exceptions.SendyError: <MagicMock name='unsubscribe()' id='140427579614256'> . How can I pass as if exception never occurred? -
how to check perform field validation in resource.py?
I am uploading a .xls file and need to check the below condition before it saves to the model/database. requirement: 1.how to count the total no of rows and compare it with some value and if len(row)<=count(any variable). 2. how to reset count variable in 1 day. resource.py class CTSResource(resources.ModelResource): class meta: Model=CTA def before_import(self, dataset, using_transactions, dry_run, **kwargs): --Logic code--- --Logic code--- I am trying to implement it at the file processing level in my views.py file as shown below. def CTA_upload(request): try: if request.method == 'POST': movie_resource = CTAResource() ##we will get data in movie_resources#### dataset = Dataset() new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'apple/uploadinfosys.html') messages.info(request, 'Uploading Data Line by Line...') imported_data = dataset.load(new_movie.read(), format='xls') count = 1 for data in imported_data: value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], ) count = count + 1 value.save() # messages.info(request, count) # time.sleep(1) messages.info(request, 'File Uploaded Successfully...') except: messages.info(request,'Same Email ID has been observed more than once.Except that other records has been added../nPlease Make sure Email field should be unique.') return render(request,'app/cta.html') -
SyntaxError: EOL while scanning string literal (I am trying to connect Django with PostgreSQL)
I am trying to connect Django to the PostgreSQL database, but this is my first time doing it, so I am not sure how exactly to do it. The problem seems to be with the line, where the password is. settings.py - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '<db_name>', 'USER': '<db_username>', 'PASSWORD: '<password>', 'HOST': 'db_hostname_or_ip>', 'PORT': 'db_port', } } When I try to make migrations in my prompt, (python manage.py makemigrations) I am getting the error mentioned in the title. Can anybody help me please? -
Triggering action on adding object from admin panel
I have a model that holds emails of users who signed up for emails that notify about new articles on the site. Articles are added from the admin panel. I want to figure out how to trigger some function on object addition by admin. MailingList model class MailingList(models.Model): email = models.CharField(max_length=50) def __str__(self): return 'email: ' + str(self.email) Thank you! -
how to use !st image from a list and all the other image separately in different for loop
Hellow everyone, In the first snippet of html, I want to show fist image and in the next loop I want to iterate from 2nd image, {% for p in photos %} {% if forloop.first %} //showing the 1st image <div class="box active" onclick="changeImage(this)"> <img src="{{p.images.url}}"> </div> {% endif %} {% endfor %} {% for p in photos %} {% if forloop.counter %} //showing from 2nd image <div class="box" onclick="changeImage(this)"> <img src="{{p.images.url}}"> </div> {% endif %} {% endfor %} Now in the 2nd snippet of html I used the first image property and then from 2nd image property {% for p in photos %} {% if forloop.first %}//for using first image property <a href="{{p.images.url}}" data-fancybox="gallery1"> <img src="{{p.images.url}}" data-name="show{{forloop.counter0}}" class="hide-image show-image" alt="big_image"> </a> {% endif %} {% endfor %} {% for p in photos %} {% if forloop.counter %}//for using 2nd image property <a href="{{p.images.url}}" data-fancybox="gallery1"> <img src="{{p.images.url}}" data-name="show{{ forloop.counter }}" class="hide-image" alt="big_image"> </a> {% endif %} {% endfor %} But my tmeplate is not working correctly,clicking on the image //onclick function is not working I am unable to find the solution,can any one please suggest me where is the problem,I tested all other parts of the html code individually and … -
Django - Include UpdateView in modal of Templateview
I have built an app that allow user to create a report about clients. Inside that app, to dsplay all the report, I have a page called report_validated.html, which is rendered by a TemplateView (by the way, should I use a ListView instead?) I allow the users to edit their report with an UpdateView that is rendered in report_update.html. So far, everything works good like this. However now, I'd like to allow the user to click on an Edit button that load a modal which will render the update form filled by the already exisiting data from the database. I have been trying to do this and I have been checking multiple posts on this website to find a solution but I have been unable to achieve it. models.py class Report(models.Model): input_title = models.CharField(max_length=200) content = models.TextField() refs = models.CharField(max_length=20) comment = models.TextField() is_noticed = models.BooleanField(default='False') tags = TaggableManager() date_of_writing = models.DateField(default=datetime.date.today) created_by = models.ForeignKey(User, related_name="report", blank=True, null=True, on_delete=models.CASCADE) views.py class ReportValidated(TemplateView): template_name = "taskflow/report_validated.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) today = datetime.date.today() context['preceding_validated_report'] = Report.objects.filter(is_noticed=True).exclude(date_of_writing=today).order_by('-id') context['validated_report_of_today'] = Report.objects.filter(date_of_writing=today).order_by('-id') return context class ReportCreate(LoginRequiredMixin, CreateView): model = Report template_name = 'taskflow/report_create.html' form_class = ReportForm success_url = None def form_valid(self, form): … -
Is it possible to make email confirmation key shorter with dj-rest-auth?
I am making a rest api for mobile application. I am using dj-rest-auth package for the overall authentication process. Overall auth functionality works fine but One thing I want to modify is to make the email confirmation key shorter. User will get email like this. Please use this key to confirm your email. MjE:1l7ZhR:f6U2RWlx2kEJY2jXzFuAuKpKclNyc3MpaKmeiEFGp3Y In my email verify api user need to enter this whole key for verification. Is there any way to make this key shorter so that it will be good from user perspective(I think) ? I have made my custom adapter here. class MyAdapter(DefaultAccountAdapter): def send_confirmation_mail(self, request, emailconfirmation, signup): current_site = get_current_site(request) activate_url = self.get_email_confirmation_url( request, emailconfirmation) ctx = { "user": emailconfirmation.email_address.user, "activate_url": activate_url, "current_site": current_site, "key": emailconfirmation.key, } -
Saving data from Views to Database
Hi I'm building a Webshop with a cart and checkout function. Now I'm trying to save the cart data in a Django Model so I can retrieve it. Now my question is how could I do that? and how can I get the data from an model? Here are my models: This is the model I want to save the data in: class MessageItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) mItem = models.CharField(max_length=255, null=True) mQuantity = models.CharField(max_length=255, null=True) # Could also be an Integer! mOrderItem = models.CharField(max_length=255, null=True) Here are my other models: class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) # Nicht nötig image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item … -
Django Oauth Toolkit: User data over introspection
Current Scenario: I'm using Introspect to validate access token on the authentication server. This call returns only 'username' of the user from the authentication server and saves it in the resource server. The Id of the same user on the authentication server and the resource server are no necessarily the same. Desired Scenario: I want to receive more data about the user (email, phone number, address, etc..) and save it in the resource server. What I have done so far: I modified the django-oauth-toolkit/oauth2_provider/views/introspect.py/ get_token_response to return the data I need. What is remaining: How do I save those data in the resource server? or is it better to make an api call to the authentication server whenever I require the user data? -
How to change the "timestamp without time zone" to "timestamp with time zone" using Django models using migrations?
class test(models.Model): mobile_last_login = models.DateTimeField() I need to change the "timestamp without time zone" to "timestamp with time zone" for the "mobile_last_login" field. -
Celery sending tasks as a group
So I have some tasks in celery that are not registered in the current process and what I am trying to achieve is to actually make a group call for multiple tasks. For example: from celery import group, Signature, signature from task_app import celery_app from celery.execute import send_task workflow = group([ send_task( 'my_task.deploy', kwargs={ 'name': 'dev1', 'site': 'somesite', 'sleep': 1 }, immutable=True, app=celery_app, )] ) result = workflow() print(result.get()) The problem is that using send_task is group will give me this error Traceback (most recent call last): File "workflows.py", line 17, in <module> result = workflow() File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/canvas.py", line 1077, in __call__ return self.apply_async(partial_args, **options) File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/canvas.py", line 1102, in apply_async results = list(self._apply_tasks(tasks, producer, app, p, File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/canvas.py", line 1182, in _apply_tasks for sig, res in tasks: File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/canvas.py", line 1163, in _prepared task = from_dict(task, app=app) File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/canvas.py", line 139, in from_dict typ = d.get('subtask_type') File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/result.py", line 223, in get return self.backend.wait_for_pending( File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/backends/asynchronous.py", line 199, in wait_for_pending for _ in self._wait_for_pending(result, **kwargs): File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/backends/asynchronous.py", line 265, in _wait_for_pending for _ in self.drain_events_until( File "/home/vladnedelcu/Desktop/asyncStuff/env/lib/python3.8/site-packages/celery/backends/asynchronous.py", line 51, in drain_events_until if timeout and time.monotonic() - time_start >= timeout: TypeError: '>=' not supported between instances of 'float' and 'str' … -
how to retrieve an object with generic relation (ContentType) in Django
I used ContentType in my django 3.1 project to implement a wishlist. here is my models.py: # Users.models.py class WishListItem(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=True, blank=True) count = models.IntegerField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I declard the genericRelation in other models ( that are from other apps). for example: another_app.models.py: # Support.models.py class Training_Lists(models.Model): title = models.CharField(max_length=50, unique=True) cover = models.ImageField(upload_to='photos/support/tranings/', null=True, blank=True) is_published = models.BooleanField(default=True) slug = models.SlugField(null=False, unique=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) tags = GenericRelation(WishListItem, related_query_name='training', null=True, blank=True) In my scenario, I want to retrieve a training object in order to get it's price. based on Django docs for ContentType.get_object_for_this_type(**kwargs), I should retireve the model type which I am looking for, then get the object with get_object_for_this_type. in the docs, it says: from django.contrib.contenttypes.models import ContentType user_type = ContentType.objects.get(app_label='auth', model='user') # <= here is my question user_type <ContentType: user> user_type.get_object_for_this_type(username='Guido') <User: Guido> here is my question: what are app_lable and model parameters? in Users.views.py I want to retrieve the price of an Training_Lists object which is added to wishlist as a WishListItem object. -
how to get the device registration_id
registration_id = "<device registration_id>" message_title = "Uber update" message_body = "Hi john, your customized news for today is ready" result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) i have 2 django apps and I want to send notification from one website to another . for this I am using pyFCM but I am not able to get the device registration_id for another device and how to use it . pyFCM -
How to Override config model in djago-constance backend.database.model in a django app
i have used django-constance package in my project. I want to add some fields the config model. Where should i write the code to override config model -
NGINX does not serve the collected static files
I am running a dockerized Django application on an AWS EC2 instance, and the page loads without the static files, even though NGINX has them collected. I find this pretty strange, as it had not happened to me until now (at least on my local machine). It would be greatly appreciated if you could help me solve this issue. This is my docker-compose.yml file: version: "3" services: web: restart: always build: . command: bash -c " python manage.py makemigrations && python manage.py migrate && python manage.py creategroups && python manage.py initializesuperuser && python manage.py collectstatic --noinput && daphne -b 0.0.0.0 -p 80 DL.asgi:application" expose: - 80 environment: - DJANGO_SETTINGS_MODULE=DL.production_settings volumes: - static_volume:/usr/src/app/DL/static/ - media_volume:/usr/src/app/media_cdn nginx: restart: always build: ./nginx ports: - "80:80" volumes: - static_volume:/static/ - media_volume:/media/ depends_on: - web volumes: static_volume: media_volume: Here's production_settings.py: STATIC_URL = '/static/' STATIC_ROOT = "/usr/src/app/DL/static/" A snippet of the file structure inside the web container (DL_app is the name of the Django app): usr | |──src | |──app | |──DL | |──DL | |──DL_app | | | |──static | |──manage.py | |──static And, lastly, here's nginx.conf: upstream web { server web:80; } server { listen 80; location / { proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; … -
C:\Users\bhanu\AppData\Local\Microsoft\WindowsApps\python.exe: can't open file
C:\Users\bhanu\AppData\Local\Microsoft\WindowsApps\python.exe: can't open file 'C:\Users\bhanu\Desktop\Python Course with Notes\django\blog\manage.py': [Errno 2] No such file or directory This error occur when I am try to runserver in django . using python manage.py runserver -
Overriding templates with same name is django
I have a app named company in django, while both the template directories i.e one in company/templates and the other in base_dir/templates have a file named index.html. when i try to render the templates index.html from company app it renders the template from base directory. I want to override this so that every app uses it's own template directory for rendering. Is there any way by which I can make this possible. I have added all template directories in settings.py Thanks in advance -
UpdateView post() returns success message even if user tries to submit disabled form field
I've made a custom django form and mark email field as disabled. If someone tries to remove readonly attribute from browser's developer console and submits the form, email isn't updated but it doesn't show error message either it just shows success_message I've in my Update view. Is there any way to handle this and return error message instead of success. Below are the code snippets class ProfileView(AdminRequiredMixin, SuccessMessageMixin, UpdateView): template_name = '/profile.html' form_class = UpdateProfileForm success_message = 'Profile Updated Successfully' and the UpdateProfileForm class UpdateProfileForm(forms.ModelForm): email = forms.CharField(disabled=True) class Meta: model = User fields = ['image', 'name', 'role', 'email'] Now i want if user tries to submit the email forcefully, it shows an error message that email isn't editable or so. -
LookupError: App 'app' doesn't have a 'CustomUser' model
So I added the following line in my settings.py: AUTH_USER_MODEL = 'app.CustomUser' And I got the error: LookupError: App 'app' doesn't have a 'CustomUser' model. The last line in error is: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.CustomUser' that has not been installed Here is my CustomerUser class in app/models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser from django.utils import timezone class CustomUser(AbstractUser): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='CustomUser') name = models.CharField(max_length=500) phone = models.CharField(max_length=30) email = models.CharField(max_length=500) class Meta: abstract = True I get this error while trying to run makemigrations. I already have an existing db, and I'm redoing my models. I tried deleting the database file, and no luck. -
How can I update the object and create one at specific time with Django?
I am building an auction website, and I need to create an Object that shows us the winner of the auction once the auction has been ended! my models.py class Auction(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) start_time = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) end_time = models.DateTimeField() #when times up Winner should be created Automatically start_price = models.DecimalField(verbose_name="Original Price", max_digits=15, decimal_places=1, default=0.0) current_price = models.DecimalField(verbose_name="Current Price", max_digits=15, decimal_places=1, default=0.0) next_price = models.DecimalField(verbose_name="Next Price", max_digits=15, decimal_places=1, default=0.0) step = models.DecimalField(verbose_name="Raise Price", max_digits=15, decimal_places=1, default=0.0) sold_price = models.DecimalField(verbose_name="Sold Price", max_digits=15, decimal_places=1, blank=True, null=True) is_active = models.BooleanField(default=True) is_manual = models.BooleanField(default=True) def __str__(self): return self.product.title class Bid(models.Model): Types = ( ('auto', 'Automatically'), ('user', 'By user own') ) auction = models.ForeignKey(Auction, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) time = models.DateTimeField(auto_now_add=True) price = models.DecimalField(verbose_name="Bid Price", max_digits=15, decimal_places=1, default=0.0) action = models.CharField(max_length=120, default="user", choices=Types) def __str__(self): return str(self.price) class Winner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) auction = models.ForeignKey(Auction, on_delete=models.CASCADE) won_price = models.DecimalField(verbose_name="Won Price", max_digits=15, decimal_places=1) won_time = models.DateTimeField() def __str__(self): return self.user.username For the auction process, I am using Django Channels which means I can create the winner if the auction page has viewers(when WebSocket is on) else I am not able to do that! Thats why I have to do it … -
creating pandas dataframe from large list of records: how to make more efficient?
I am creating an epidemiological model which takes inputs and produces outputs. A standard output is a python dictionary with the following information { 'Location': 'Australia', 'Age group': '1 to 4', 'Sex': 'm', 'Cancer': 'cervical', 'Stage': 'stage IV', 'Coverage': 'Covered', 'Year of cohort': 2022, 'Year': 2025, 'Mortality': 0.0 } However, the current model produces 330,000 dictionaries which look like this. I'd like to create a dashboard using this information, which maintains the data in each entry. My first thought was to create the dataframe iteratively as follows: pd.DataFrame([x for x in huge_list_of_dictionaries], index=[0]) This produces the intended result, but takes several minutes to aggregate the data (using my personal computer, intel i7, nothing fancy). The hope is that this data can be used fairly quickly in a webapp using django, so reducing the speed is essential. I have had two thoughts about quicker solutions, Encode the strings as integers (e.g. male sex = 0), then remap the data once in the dataframe, or even when plots are generated. Have an intermediary step where the relevant data is selected (e.g. only prostate cancer) and only return this data Is there a more obvious solution that I am missing? -
I have a problem when I submit product in the cart with AJAX / Django
I can't submit product in the the cart when I use AJAX without refreshing page. When I submit JSONPage will be displayed. I'm trying to use AJAX first. Trying to add product in the cart without refreshing page. I need help please :) Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({'status': 'success'}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> JS Code products = document.querySelectorAll('.buy-product') for (var i=0; i < products.length; i++){ $(products[i]).on('submit', function(){ var product_id = $(this).attr('data-id') var quantity = 1 console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id/ $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, method: HttpMethod, type: 'POST', data: data.serialize(), success: function(data){ console.log('success') console.log(csrftoken) } }) }) } -
display multiple django messages in one page?
I have a template in which user can change his details like name, email and password. I am getting wrong messages after updating info ( if I change the password then I got message "Invalid" that is part of edit_profile) though I used extra_tags for message to identify two different messages, But still having issue. I tried searching a lot, and found some relevant questions but was not helpful. views.py def edit_profile(request): if request.user.is_authenticated: if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.success(request, "Update successful!", extra_tags='edit_profile') return redirect("accounts:edit_profile") else: messages.error(request, "Invalid", extra_tags='edit_profile') return redirect("accounts:edit_profile") else: form = EditProfileForm(instance=request.user) return render(request, "accounts/edit_profile.html", {'form': form}) else: redirect('accounts:signin') def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() messages.success(request, "Update successful!", extra_tags='change_password') update_session_auth_hash(request, form.user) return redirect("accounts:change_password") else: messages.error(request, "Password Error", extra_tags='change_password') return redirect("accounts:change_password") else: form = PasswordChangeForm(user=request.user) return render(request, "accounts/edit_profile.html", {'form': form}) template <h2 class="font-weight-bolder">Account Details</h2> <!-- edit_profile form --> <form action="{% url 'accounts:edit_profile' %}" method="post" class="row g-3 needs-validation" novalidate> {% csrf_token %} <!-- 1 Username --> <div class="offset-md-2 col-md-4 "> <label for="username" class="form-label">Username</label><br> <input type="text" name="username" class="form-control" id="username" value="{{ form.username.value }}" required> <div class="invalid-feedback"> Please provide name. </div> </div> <!-- 2 Email --> <div class="offset-md-1 col-md-4"> … -
Django Multiple Types of Users, one base usertype?
I am attempting to create a food delivery app clone. Which has two types of users Restaurant User and Customers. I want the restaurant user to be able to also be customers, using the same login info. This is how my models are setup right now: class Restaurant(models.Model): user_name = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant') full_name = models.CharField(max_length=500) phone = models.CharField(max_length=500) employee_id = models.CharField(max_length=500) class Customer(models.Model): user_name = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customer') full_name = models.CharField(max_length=500) email = models.CharField(max_length=500) avatar = models.CharField(max_length=500) phone = models.CharField(max_length=500) address = models.CharField(max_length=500) I don't believe this works as intended. Would it be better to create a base usertype, for login and shared information, like user_name, full_name, phone? I created the following for that purpose: class CustomUser(AbstractUser): user_name = models.OneToOneField(User, on_delete=models.CASCADE, related_name='CustomUser') full_name = models.CharField(max_length=500) phone = models.CharField(max_length=30) But I'm not sure how to connect this between the other user models. Or if this is even the proper way to do it. So how can I achieve what I am trying to do, what would my models look like? -
How to insert Year choices in DateInput Widget?
I have a current widget like this: date_fr= forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) Which renders a simple datepicker on template (input type=date) However, I dont know how to limit the years. my choices: YEAR_CHOICES = [] years = calendar.get_year(0) #calendar.get_year separate py function to get the years for i, x in enumerate(years): print(x) YEAR_CHOICES.append(([x, x])) My other form: forms.DateField(widget=forms.SelectDateWidget(years=YEAR_CHOICES)) Does limit the years but it separates the month, day and year on three separate select drop downs.