Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django PostUpdateView isn't saving image ValueError thrown
In models.py I have: class Post(models.Model): title = models.CharField(max_length=100) post_content = models.TextField(max_length=10000) date_posted= models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='blog-post-images/', blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 500 or img.width > 500: if img.height > img.width: factor=500/img.height nH=500 nW=img.width*factor output_size= (nH,nW) if img.width > img.height: factor=500/img.width nW=500 nH=img.height*factor output_size= (nH,nW) else: output_size=(500,500) img = ImageOps.exif_transpose(img) img.thumbnail(output_size) img.save(self.image.path) And then in views I have: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'post_content', 'image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post=self.get_object() if self.request.user == post.author: return True return False Upon runserver, page renders html with form fields just fine, allows me to select image path, but then the error I get thrown when actually submitting image path is: "ValueError at /home/post/10/update/ The 'image' attribute has no file associated with it." And image doesn't save. However, when I do it through admin it does save image. I have image blank and null bc I want image to be optional attribute. Is this the reason I'm getting issues? Does something extra need to be added to PostUpdateView class? Thank … -
Make the output of Django runserver flush in Git Bash
When I issue python manage.py runserver under Git Bash, only one line of output appears: Watching for file changes with StatReloader The remaining output appear when I either stop the server or make a change in the code: Performing system checks... System check identified no issues (0 silenced). September 01, 2021 - 23:11:21 Django version 3.2.7, using settings 'newserver.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. How do I make it flush right away? -
Python: How to query a dictionary using a variable as a key
I have a list from a Django model, which can have dict_items with any key, from the model. E.g. I can have a list with 'country' attribute, or 'name' attribute from the same model using a function. x = dict_items([(<country: US>, 1), (<country: UK>, 1), (<country: Australia>, 2), (<country: Canada>, 1)]) x = dict_items([(<name: John>, 10), (<name: Jane>, 15), (<name: Smith>, 20), (<name: Jess>, 1)]) Now, I am trying to build another function to cleanup the keys, basically (<country: US>, 1) to {'key': 'US', 'val': 1} def pctTop5 (dict, keyy): pList = [] for (key,value) in dict: pdict = {} pdict['key'] = key.keyy pdict['val'] = value pList.append(pdict) df = pandas.DataFrame(pList) return df However, I am getting the following error: 'countryModel' object has no attribute 'keyy' 'countryModel' object here is the Django model, which obviously does not have an attribute called 'keyy'. What would be the correct way to pass a variable in order to query a dict key? I need to pass the variable as a key an reuse the function is different views. I tried searching, but most of the answers are for using variable to create a list of dicts, but couldn't find any to query one. TIA -
didn't return an HttpResponse object. It returned None instead Stripe Checkout
I have a problem because I can not make Stripe work with my django project. As in title I get an error. It is really rough to integrate Django with the Stripe. ValueError at /create_checkout_session The view shop.views.create_checkout_session didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/create_checkout_session Django Version: 3.2.6 Exception Type: ValueError Exception Value: The view shop.views.create_checkout_session didn't return an HttpResponse object. It returned None instead. views.py def create_checkout_session(request): MY_DOMAIN = 'localhost:8000' if request.method == 'POST': try: cart = Cart.objects.filter(order_user=request.user) stripe.api_key = os.environ.get('stripeAPI') checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': 'price_1JUTtYIXuOafNhy8tmWVwgjG', 'quantity': 1, }, ], payment_method_types=[ 'card', 'p24', ], mode='payment', success_url=request.build_absolute_uri(reverse('success-page'))+ '?session_id={CHECKOUT_SESSION_ID}', cancel_url= request.build_absolute_url(reverse('cancel-page')), ) except Exception as e: return str(e) return redirect(checkout_session.url, code=303) -
Django Saving Path into Variable
I have a django path that passes the URL I need, but I want to store it into a variable which I can use in a mailing API the path is: path('activate/(<uidb64>[0-9A-Za-z_\-]+)/(<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})', views.activate, name='activate'), I want the string to have a value similar to this: http://127.0.0.1:8000/auth/activate/(NDM%5B0-9A-Za-z_%5C-%5D+)/(as9osn-a59ae3d7196bb1fa693e770fb87f19c1%5B0-9A-Za-z%5D%7B1,13%7D-%5B0-9A-Za-z%5D%7B1,20%7D) I am getting this: http://127.0.0.1:8000/auth/activate/NTQ/asbda1-165d68dbe6fee8c47f5099c4ab709c48 -
calc between points in django postgis
i have a model: class lctnp(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pin = gmodel.PointField(geography=True, null=True, srid=4326) description = models.TextField() class Meta: ordering = ['created_at'] and input with: { "id": "", "owner": "1", "pin": "POINT(-95.3385 29.7245)", "description": "hello from here" } and try to calc distance with another point: query = ''' SELECT id, ST_Transform(pin, 4326), ST_Distance(pin, 'SRID=26918;POINT(-95.3385 30.7245)') AS dist FROM house_lctnp ORDER BY pin <-> 'SRID=26918;POINT(-95.3385 30.7245)'::geometry LIMIT 3; ''' for p in lctnp.objects.raw(query): return JsonResponse(p.description, safe=False) but seems i try a wrong way. plz help me -
Docker and Django Rest Framework "unexpectedly dropped the connection"
Overview I have a weird situation where when I apply DEFAULT_FILTER_BACKENDS to my Django Rest Framework (DRF) settings, I get a "Safari can't open 0.0.0.0:8000 because the server unexpectedly dropped the connection" error message. I should note that the config below works perfectly with a standard poetry run python manage.py runserver 0.0.0.0:8000 command, i.e. when I don't use Docker. My Django settings.py file is standard, except for: INSTALLED_APPS = [ ... "rest_framework", ... ] REST_FRAMEWORK = { "DEFAULT_FILTER_BACKENDS": ( "django_filters.rest_framework.DjangoFilterBackend", ), } and when I remove/comment out the "DEFAULT_FILTER_BACKENDS" section, the server works and my pages load perfectly. Dockerfile # pull official base image FROM python:3.9.0-buster # set work directory WORKDIR /usr/src/app # set environment variables ENV DJANGO_SETTINGS_MODULE=barrys_project.settings ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --no-cache-dir --upgrade pip RUN pip install --no-cache-dir poetry COPY ./poetry.lock ./pyproject.toml ./ RUN poetry config virtualenvs.create false RUN poetry install # copy entrypoint.sh COPY ./entrypoint.sh ./ # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] Docker Compose file version: '3.8' services: web: build: ./ volumes: - ./:/usr/src/app/ command: poetry run python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 env_file: - ./.env depends_on: - db db: image: postgres:13.3-alpine volumes: - … -
Django ArrayField - Choices from a class of constants - ERROR fields.E005
I have a file with constants declared inside classes: class LanguageChoices: EN = "English" FR = "French" @classmethod def choices(cls): return ( (cls.EN, _("English")), (cls.FR, _("French")), ) And my models: from django.contrib.postgres.fields import ArrayField from apps.users.constants import LanguageChoices class Data(models.Model): language = ArrayField( models.CharField( max_length=30, choices=LanguageChoices.choices()), blank=True, null=True ) ) When I try to run migrations it run into this error (this happens even if I erase all previous migration files and use a new database): SystemCheckError: System check identified some issues: ERRORS: users.Data.language: (postgres.E001) Base field for array has errors: 'choices' must be an iterable containing (actual value, human readable name) tuples. (fields.E005) ERROR: 1 Any ideas? -
Unable to use custom account adapter
I have the following in adapter.py: from allauth.account.adapter import DefaultAccountAdapter class CustomAllauthAdapter(DefaultAccountAdapter): pass # keeping it trivial for debugging At the very end of settings.py: import django django.setup() # complains about apps not being loaded yet without this... from .adapter import CustomAllauthAdapter ACCOUNT_ADAPTER = CustomAllauthAdapter # this is the line that results in the error! As soon as I submit the registration form for a new user, I get this error in the browser: AssertionError at /api/v1/users/auth/register/ No exception message supplied Here is the Traceback: File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\views.py", line 47, in dispatch return super().dispatch(*args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\generics.py", line 190, in post return self.create(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\views.py", line … -
Get id from a card created in a crud django-oracle
I want to obtain the id code of a specific card when I select it so that it will then give me information. The card is created through a crud, so it is dynamic. I use oracle database. I got undefined in the alert. This is my template <section class="cards"> {% for c in Comidas %} <div class="card"> {% if c.imagen %} <img class="card__image" src="data:imagen/png;base64, {{ c.imagen }}" alt=""> {% endif %} <div class="card__title">{{ c.data.1 }}</div> <div class="card__id" id="id_Card" onclick="obtenerId()">Codigo Orden: {{ c.data.0 }}</div> <div class="card__snippet">{{ c.data.2 }}</div> <div class="card__description">{{ c.data.3 }}</div> <a href="comida_details" class="card__readmore">Detalles</a> </div> {% endfor %} </section> <script> function obtenerId(){ let id= document.getElementById("id_Card").value; alert(id) } </script> Thank you very much for your help -
When select different options shows different input, but all inputs of all options are required
I'm working with Django and I made a function that creates a person (employee, student, or worker) and as you can see I created the three different forms on create_person, so on the template, when you select an option on school_role to choose what kind of person you will create, its shows different inputs and select, it depends if you click on student, academic or employee. This is ok, but my problem is that I need to fill all of the inputs and selects on all of the three options to be able to send the form, and I need that you just have to fill one ( employee, academic, or student). def create_person(request): if request.method == 'POST': form = PersonForm(request.POST) daysform = AvailableDayForm(request.POST) studentForm = StudentForm(request.POST) academicForm = AcademicForm(request.POST) employeeForm = EmployeeForm(request.POST) if form.is_valid() and daysform.is_valid(): data = form.save() daysform.save(id=data.id) id = data.id if(data.school_role==1): if studentForm.is_valid(): studentForm.save(id = id) messages.success( request=request, message='success' ) return redirect('cases:list') elif(data.school_role == 2): if academicForm.is_valid(): academicForm.save(id = id) messages.success( request=request, message='success' ) return redirect('cases:list') else: if employeeForm.is_valid(): employeeForm.save(id = id) messages.success( request=request, message='success' ) return redirect('cases:list') else: form = PersonForm() daysform = AvailableDayForm() studentForm = StudentForm() academicForm = AcademicForm() employeeForm = EmployeeForm() context = … -
How to present excel document in datatables?
I'm working on a project, and I need to present data in web page from excel with multiple sheets (multiple documents). Is it possible with this https://datatables.net/ and how? I have tried with this but something is wrong, only get me confused. I wasn't able to run the example that they have been prepared. Any ideas how to present excel document with multiple sheets online with django? -
How to reverse the list inside django template?
I have a list and I wanted to order by descinding in django-html template, How can I do it ? This is my template code {% for unique_date in unique_dates %} <th>{{unique_date}}</th> {% endfor %} And this is my view file unique_dates = list({a.date for a in attendances}) unique_dates.sort() -
Django sessions instead of user model
Is there a way to use sessions in django instead of a user model? I know django creates sessions for each "new" client accessing the server. I want to be able to store attributes like I would on a user model and be able to retrieve a session based on a form. more like logging in an existing session on a "new" client. Whats the most elegant approach? I'm thinking of implementing a middleware -
Sorting DataTable by recent date
I have a table and it is sorted by the old date. I just want to make its default sorting is the recent date. the code is: <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }); }); </script> and it looks like: I tried many solutions on the net but all didn't work! <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }).asSorting([[0, "desc"]]); }); </script> and this <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }).fnSort([[1, "acs"]]); }); </script> and this too <script> $(document).ready( function () { $('#table_id').DataTable({ "order": [[ 3, "desc" ]] dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }); }); </script> and this one > <script> > $(document).ready( function () { > $('#table_id').DataTable({ > "aoColumnDefs": [ > { "asSorting": [ "asc" ], "aTargets": [ 0 ] } > ] > dom: 'B<"clear">lfrtip', > buttons: { > name: 'primary', > buttons: [ 'copy', 'csv', 'excel', 'pdf' ] > } > }); }); </script> any suggestions? -
Django ManifestStaticFilesStorage and imports within javascript files
The Django 3.2 ManifestStaticFilesStorage adds a hash value to javascript files called from within a template and this is working as expected. However, some javascript files import from other javascript files and those imported filenames are not translated to a hashed value. The ManifestStaticFilesStorage documentation indicates that this is done for for CSS files when it finds the import rule and url() statement but is silent on how to do it for javascript. Any suggestions on how to get this to work? As an example, this line in the html template: <script src="{% static 'myapp/js/myjavascript.js' %}" type="module"></script> is rendered like this in the browser (works as expected): <script src="/static/myapp/js/myjavascript.12345abc.js" type="module"></script> But within the myjavascript.js file, this line is left untouched, meaning that the browser could still have a cached version of the imported javascript file and use that instead of an updated version. import {func1, func2, func3} from './javascript_helper_lib.js'; -
django adds 127.0.0.1 to the links while running on a real server and not real web address
I run django on a Nginx server. The website is available at this address on the internet: www.website-example.com I have some links in one of the pages. But when I click on the I get this: 127.0.0.1:8000/books/book1.jpeg I should get the below address: www.website-example.com/books/book1.jpeg my allowed hosts in setting is like below: ALLOWED_HOSTS = ['www.website-example.com', '127.0.0.1'] What is wrong that I still get 127.0.0.1? I also removed 127.0.0.1 but the website stops working and says you should add 127.0.0.1 to allowed hosts. -
user with only password required
I want the user to authenticate only with his password and a field from another model that is not shown.I have here the BaseUser of django that I am trying to customize. In the code following the password and email are required.I don't want email to be required anymore class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("L'adresse e-mail donnée doit etre definie") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True") return self._create_user(email, password, **extra_fields) class User(AbstractUser): username = None email = models.EmailField('email adress', unique=True) telephone = models.CharField(max_length=20) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] I want only the password to be required. What should I do so that the email is no longer required? -
Nothing happens after hitting the form button , how to return to the main page of the site after payment? [Django]
i'm studying django and i'm trying to get some practice with this e-commerce site. The problem I have is that at the time of paying with the card (in reality it is not a real payment) the user should be redirected to the home page but in reality nothing happens. Can you help me ? These are the main files. models.py from django.db import models from django.contrib.auth.models import User class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=50) image = models.ImageField(upload_to="admins") mobile = models.CharField(max_length=20) def __str__(self): return self.user.username class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) address = models.CharField(max_length=200, null=True, blank=True) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Category(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to="products") selling_price =models.DecimalField(max_digits=10,default=0,decimal_places=2,null=True) marked_price = models.DecimalField(max_digits=10,default=0,decimal_places=2,null=True) description = models.TextField() warranty = models.CharField(max_length=300, null=True, blank=True) return_policy = models.CharField(max_length=300, null=True, blank=True) view_count = models.PositiveIntegerField() def __str__(self): return self.title class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to="products/images/") def __str__(self): return self.product.title class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) total = models.DecimalField(max_digits=10,default=0,decimal_places=2,null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Cart: " + str(self.id) class CartProduct(models.Model): cart = models.ForeignKey(Cart, … -
Integrating Stripe - JSONDecodeError
Hello I am integrating stripe with my Django App and i struggle, because I get an error. I put all of the code which I think is needed for Stripe integration. I would be pleased for any advice. ERROR: "JSONDecodeError, Expecting value: line 1 column 1 (char 0) " views.py @csrf_exempt def create_checkout_session(request, pk): request_data = json.loads(request.body) cart = Cart.objects.filter(order_user = request.user) stripe.api_key = os.environ.get('stripeAPI') checkout_session = stripe.checkout.Session.create( customer_email = request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'product_data': { 'name': cart.order_items, }, 'unit_amount': cart.total, }, 'quantity': 1, } ], mode='payment', success_url=request.build_absolute_uri( reverse('success-page') ) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('cancel-page')), ) HTML template: <form action="{% url 'checkout-page' 5 %}" method="GET"> <button type="submit">Checkout</button> </form> URL path: path('create_checkout_session/<int:pk>', views.create_checkout_session, name='checkout-page'), models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) class Item(Visits, models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) total = MoneyField( default=0.00, decimal_places=2, max_digits=11, default_currency='USD') -
Where is ID saved in django ModelAdmin autocomplete_fields?
I am rewriting some administration interface to django 2.2, currently using django autocomplete_fields admin feature. Simply said I have ModelAdmin object OrderAdmin, which has nested TabularInline ProductAdmin: variable-length table of products which might be added to order. Each of these ProductAdmin holders just contains ForeignKey to actual product class, with some other attributes. Now I wonder: where does django store id - ForeignKey - of item selected with autocomplete field? It doesn't mark OPTION in selectbox as selected, and although there is suspicious hidden input field with #cashregisterproduct_set-0-id on page, it doesn't have any value. Or is there some special way how to access it? I was thinking about adding id to __str__ method of model and parsing, but thats just ugly. Thanks for tip. -
How to get the current projct_id in Django
I have a view where in the options input I want to list just those users who related to the current project but I can't. I don't know how to write a query that list just these users without I use the project_id from the url. I don't want the projekt_id in the url. This is the point, where I stuck: views.py def kapcsolodasok(request, projekt_id): if request.method == 'POST': kap_bar_01 = request.POST.get('kap_bar_01') kap_bar_02 = request.POST.get('kap_bar_02') kapcsolodasok = kapcsolodasok(kap_bar_01=kap_bar_01, kap_bar_02=kap_bar_02) kapcsolodasok.save() related_users = Profile.objects.raw('SELECT stressz_profile.id, last_name, first_name, stressz_profile.projekt_id FROM stressz_projekt JOIN stressz_profile ON stressz_projekt.id = stressz_profile.projekt_id JOIN auth_user ON auth_user.id = stressz_profile.user_id WHERE stressz_projekt.id = %s', [projekt_id]) //how to replace projekt_id with the related projekt_id of the request.user context = { 'related_users': related_users, } return render(request, 'stressz/kapcsolodasok.html', context) models.py class Kapcsolodasok(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) kap_bar_01 = models.TextField(max_length=200) kap_bar_02 = models.TextField(max_length=200) class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=3) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) date = models.DateField(auto_now_add=True, … -
Unable to import DefaultAccountAdapter from settings.py
I would like to use a custom account adapter, but as soon as I import: from allauth.account.adapter import DefaultAccountAdapter in settings.py, I get the error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is the whole error dump: (env) (base) C:\Dropbox\Parnasa\Web\drmeir>python manage.py runserver 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 "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\meir\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Dropbox\Parnasa\Web\drmeir\mysite\settings.py", line 180, in <module> from allauth.account.adapter import DefaultAccountAdapter File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\allauth\account\adapter.py", line 17, in <module> from django.contrib.auth.models import AbstractUser File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\contrib\auth\models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\contrib\auth\base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\db\models\base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File … -
Django REST Framework : How to define a viewset
Context I have two viewsets, with their own routers to automatically generate the URLs from them : ModelAViewset ModelBViewset For now, the ModelAViewset details can be retrieved through the following URL : {base_url}/model-a/<slug> With '<slug>' being the ModelA 'slug' field, as a lookup_field. Questions Is there a way to use a more explicit lookup_field value, dynamically based on the model name ? Like this : {base_url}/model-a/<model_a_slug> Note : To keep it simple in the model, I would rather like to leave the 'slug' field name of ModelA as is Based on Viewsets and Routers, is there a way to retrieve the JoinRequestViewset details through a multi lookup_fields ? With an URL like : {base_url}/model-a/<model_a_slug>/model-b/<model_b_pk> Thanks, by advance -
cart session in django
I use the session to create a shopping cart. I have a product model and a model for Variant, which I color and size my products in the Variant model. So that I can have products with different colors and sizes as well as different prices. The shopping cart I created with Session has a problem. The problem I have is that if the product has 3 different colors and each color has a different price, I have trouble displaying the price in the cart and I do not know how to act. How should I display the prices of my Variant model in the template? my Product model: class Product(models.Model): name = models.CharField(max_length=200) price = models.IntegerField(default=0) my Variant model: class Variants(models.Model): name = models.CharField(max_length=100) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_var',) size = models.ForeignKey(Size, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE) price = models.IntegerField(default=0) my session cart : CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product def add(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: …