Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Custom action functions in GenericViewSet or Viewset
I am trying to implement a basic messaging system. User can get unread/read/sent messages. Each of these routes also returns a different serialized jsons. So I do not have one serializer for the whole ViewSet. To do this I tried to implement ApiView which does not allow me to create custom actions. So I tried Viewset, viewset never hits get_serializer_class (I need this as I need different serialized models returned. So I tried GenericViewSet which seems to work. But Since get_queryset or queryset need to be implemented. I am doing the following. I am checking the action in def get_queryset(self): if self.action is 'unread': return Message.objects.filter(recipient=user,recipient_deleted_at=None,read_at=None) elif self.action is 'recieved': return Message.objects.filter(recipient=user,recipient_deleted_at=None) elif self.action is 'sent': return Message.objects.filter(sender=user,recipient_deleted_at=None) And one of the action is like so def unread(self,request): user = self.request.user message_set=Message.objects.filter(recipient=user,recipient_deleted_at=None,read_at=None) serializer = MessageSerializerFlatList(message_set, many=True) return Response(serializer.data) This works great but again I am querying the db twice, one in the unread action and also once in the get_queryset function. Is there a way to access the returned data from get_queryset function so I do not have re query the information. I mean I can hack the get_query set and just return None and do my db operations in … -
Django automatically converting double quotes to single quotes in text field
I have a very basic django view and serializer and a Postgres database in conjunction with a popular package, dj-stripe. Dj-stripe is saving some json data in a textfield in the database, and it looks like so, with double quotes: {"address":{"city":null,"country":null,"line1":null,"line2":null,"postal_code":"94303","state":null},"email":null,"name":"Jenny Rosen","phone":null} Unfortunately, it seems that something (django? python?) is converting it to single quotes, (and adding some spaces after colons) as so: {'address': {'city': None, 'country': None, 'line1': None, 'line2': None, 'postal_code': '94303', 'state': None} My view is very basic: class GetCustomerView(generics.ListAPIView): authentication_classes = (TokenAuthentication,) PaymentMethodSerializer def list(self, request): customer = Customer.objects.get(subscriber=request.user.organization_id) cards = PaymentMethod.objects.filter(customer=customer.djstripe_id) serializer = PaymentMethodSerializer(cards, many=True) pprint(serializer.data) if cards: return Response(serializer.data) else: return Response('error', status=status.HTTP_400_BAD_REQUEST)` and my serializer is basic too: class PaymentMethodSerializer(serializers.ModelSerializer): card = json.loads(serializers.JSONField()) billing_details = json.loads(serializers.JSONField()) class Meta: model = PaymentMethod fields = ( 'id', 'billing_details', 'card',) Obviously it would probably be best stored in a JSONB field, but changing the package is not an option. That said, how do I go about preventing this conversion? -
DRF: Unable to make authenticated calls with token in header
I have a list view that is authenticated but whenever I try to make a request with the token in the header, I get a 400 error. Any ideas? list view class EventListView(ListAPIView): authentication_classes = () permission_classes = (IsAuthenticated, ) serializer_class = EventFilterSerializer ... Postman Screenshot -
Is it possible in Django to grab a field from the first foreign key?
I'm trying to optimize my Django query. Right now, I'm grabbing all products, then looping through them and making a separate query for the 'feature' image url. Is there a way to grab the url for the 'Image' foreign key object where feature = True in the original query? Current Code: products = Product.objects.values('id') for product in products: image_url = Image.objects.filter(product=product["id"]).order_by('-feature').values("url").first().get("url", None) print(image_url) What I wish I could do: products = Product.objects.values('id', 'images__url') for product in products: print(product["images__url"] When I try this, it seems to return a Product for each Image, which is not at all what I want. To remedy this I tried to add a .distinct('id') on the end, but then I got this error: NotImplementedError('annotate() + distinct(fields) is not implemented.') After that I wasn't sure how to proceed, or if this is possible? Models (for reference): class Product(models.Model): title = models.CharField(max_length=255) class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, related_name="images") url = models.CharField(max_length=255, blank=True) feature = models.BooleanField(default=False) Any help much appreciated! -
What does this mean in the django documentation about class-based views?
A rookie here. As I am reading the django documentation, I came up with a note that I cannot fully understand. It says: Note While your class is instantiated for each request dispatched to it, class attributes set through the as_view() entry point are configured only once at the time your URLs are imported. Here is the link: https://docs.djangoproject.com/en/2.2/topics/class-based-views/intro/ So which one is better? What advantage does each have? I've tried both and cannot experience any difference(Pretty sure that's because I've not considered enough) -
Pillow not uploading pictures in Django
I am not sure what i am doing wrong below but Pillow is not uploading the picture when I edit a user profile. from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db import models from django.core.validators import RegexValidator from PIL import Image class CustomUser(AbstractUser): GENDER_CHOICES = ( ('Male', 'Male'), ('Woman', 'Woman'), ) profile_picture = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.CharField(max_length=200) phone_number = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{1,10}$')]) is_host = models.BooleanField(default=False) gender = models.CharField(max_length=30, choices=GENDER_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) forms.py from django.contrib.auth import get_user_model from django.forms import ModelForm from django import forms from users.models import CustomUser User = get_user_model() class EditProfileForm(ModelForm): class Meta: model = CustomUser fields = [ 'username', 'first_name', 'last_name', 'bio', 'phone_number', 'gender', 'profile_picture', ] views.py def edit_profile(request, id): """Update user profile.""" user = get_object_or_404(User, id=id) form = EditProfileForm(request.POST or None, instance=user) if form.is_valid(): form.save() messages.success(request, 'Your account was updated successfully') return redirect('users:profile') context = {'form': form} return render(request, 'users/edit-profile.html', context) project-urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls', namespace='users')), path('', include('core.urls', namespace='core')), path('auth/', include('django.contrib.auth.urls')), ] # Media Files URL if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py # Static files STATIC_ROOT = os.path.join(BASE_DIR, … -
How can I serialize an object in queryset TruncYear Django 1.11
I manage to get time series data with TruncYear/TruncMonth/TruncDay/etc like below from Tracking table. However the data for the venue just produce the venue_id. I would like to have that serialized so that it returns the "name" from the relation Venue table. I am using Django 1.11 a postgres 9.4 Here is my time series code: tracking_in_timeseries_data = Tracking.objects.annotate( year=TruncYear('created_at')).values('year', 'venue_id').annotate( count=Count('employee_id', distinct = True)).order_by('year') return Response(tracking_in_timeseries_data, status=status.HTTP_200_OK) currently it output like this: [ { "venue_id": 4, "year": "2017-01-01T00:00:00Z", "count": 1 }, { "venue_id": 2, "year": "2018-01-01T00:00:00Z", "count": 2 }, { "venue_id": 6, "year": "2019-01-01T00:00:00Z", "count": 1 } ] I want to explode venue data to return the id & name like this: [ { "venue": { id: 4, name: "room A" }, "year": "2017-01-01T00:00:00Z", "count": 1 }, { "venue": { id: 2, name: "room B" }, "year": "2018-01-01T00:00:00Z", "count": 2 }, { "venue": { id: 6, name: "room C" }, "year": "2019-01-01T00:00:00Z", "count": 1 } ] How to explode the "venue" to return the id and name. The name is useful for presentation purpose. -
range() on QuerySet
I am trying to add a progress bar to a loop of Django objects. So I need to put the list (QuerySet) in range() so I can get the number of total loop iteration. Code: rows = DjangoObjects.objects.all() for i in tqdm(range(rows)): row = rows[i] ... Error: range() integer end argument expected, got QuerySet. -
Errors not being logged to txt file
Hi have the following code in my setting.py file. Upon a 500 error, an email gets sent out with the details of the error, an error.txt file gets created in the directory noted below, but the txt file is empty. No errors are being written to this txt file. Any thoughts? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/home/jasonhoward/webapps/myproject/jason/errors.log' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': False, }, } } -
Performing calculation in a one to many relationship
I have two models and I try to subtract the value of one field with the other when a form is updated. The fields are in separate models, I have a form that is used to save the changes made to NewLeave model and I want to be able to subtract the value of Leave_current_balance in Leave_Balance model with the Total_working_days in the NewLeave model and save the update Leave_current_balance value. Currently, when the form is updated I want to call the calculateBalance method which performs the calculation but it is not working. class Leave_Balance(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, ) Outstanding_balance = models.FloatField(null=True, blank=True, default=None) Monthly_entitlement = models.FloatField(null=True, blank=True, default=None) Monthly_consumption = models.FloatField(null=True, blank=True, default=None) Leave_current_balance = models.FloatField(null=True, blank=True, default=None) class NewLeave(models.Model): user = models.ForeignKey(User, default='', on_delete=models.CASCADE) leave_balance = models.ManyToManyField(Leave_Balance) Total_working_days = models.FloatField(null=True, blank=False) def unitDirectorForm(request, staffs_id): if request.method == 'POST': getstaffid = NewLeave.objects.get(id=staffs_id) form = DirectorForm(request.POST, instance=getstaffid) if form.is_valid(): calculateBalance(getstaffid) form.save() return HttpResponse('You have successfully Authorise the leave') else: getstaffid = NewLeave.objects.get(id=staffs_id) form = DirectorForm(instance=getstaffid) return render(request, 'director_authorize_form.html', {'form': form}) def calculateBalance(staff_id): update_balance = staff_id update_balance.leave_balance.Leave_current_balance = update_balance.leave_balance. Leave_current_balance - update_balance.Total_working_days update_balance.save() -
Failing to find views when using slugs and class based views
One of my Django apps, "Pages", has many different classes in the models.py. Each of them have a slug attribute/field of their own. I'm able to load the URL for the first - "company" (first class) but for some reason can't load the other URLs. I have tried importing the views separately and creating urls paths for each view. When doing this, only the last URLs (third one) would load. models.py class Industry(models.Model): industry = models.CharField(max_length=140, null=True, blank=True, unique=True) slug = models.SlugField(max_length=40, null=True, blank=True) def __str__(self): return self.industry def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.industry) super(Industry, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('industry_detail', args=[(self.slug)]) class Subindustry(models.Model): subindustry = models.CharField(max_length=140, null=True, blank=True, unique=True) industry = models.ForeignKey( Industry, on_delete=models.CASCADE, related_name='ParentIndustry', ) slug = models.SlugField(max_length=40, null=True, blank=True) def __str__(self): return self.subindustry def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.subindustry) super(Subindustry, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('subindustry_detail', args=[(self.slug)]) class Company(models.Model): name = models.CharField(max_length=50, blank=False, unique=True, default=(str(id))) website = models.URLField(max_length=100) ... slug = models.SlugField(max_length=40, null=True, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(Company, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('company_detail', args=[(self.slug)]) views.py from django.views.generic import DetailView from django.urls import reverse_lazy # Create your views … -
how to handle this syntax error in django project
I have transferred my Django project onto Linode server already. The project was developed in VS, within anaconda (base) environment on my Mac. After I downloaded it onto the Linode server when activating it, it gave me too many dependencies (not all needed it seemed). One of them prevented me from completing the process. So, I sudo installed (in venv) needed packages (within the project’s virtual environment), for example: certifi, chardet, Django…, …. After creating ’static’ in the settings.py, on the linode server, I tried to collect static : ~$ python manage.py collectstatic BUT I am getting this Error message: enter image description here PastedGraphic-1.tiff Any idea how to fix it? """ /home/..../django/users/models.py", line 16 return f'{self.user.username} Profile' ^ SyntaxError: invalid syntax """ -
Django model FileField is set to "null" instead of url to the file when using Google Cloud Storage
I am running a File manager app on Local machine using Google Cloud Sql Proxy and storing the files in a Google Cloud Storage bucket. The file is being saved in the bucket, but the FileField is set to "null". I want it to show the url by which I can access the file. I am following this answer Configure Django and Google Cloud Storage? I have set the Google Cloud Storage bucket to public. Django Model: class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') Setting.py: #MEDIA_URL = "/media/" #MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'printhub-files' GS_PROJECT_ID = 'preasy-53c43' GS_MEDIA_BUCKET_NAME = 'printhub-files' # GS_STATIC_BUCKET_NAME = '<name-of-static-bucket>' # STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME) Expected Result: { "id": 13, "docfile": "https://storage.googleapis.com/bucket/documents/2019/11/03/myfile.pdf", } Actual Result: { "id": 13, "docfile": null, } If I change my Settings.py to (uncomment line 1,2. Comment line 4), the file is saved on my local machine media/ folder, and "docfile" is set to the bucket url: MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'printhub-files' GS_PROJECT_ID = 'preasy-53c43' GS_MEDIA_BUCKET_NAME = 'printhub-files' # GS_STATIC_BUCKET_NAME = '<name-of-static-bucket>' # STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME) I get the output: { "id": 13, "docfile": "https://storage.googleapis.com/bucket/documents/2019/11/03/myfile.pdf", } -
Looping through Amadeus API using Django
I have fetched data into my template in Django But Looping though it has been a serious issue. How should get the value like departure, iataCode and likes. [{'type': 'flight-offer', 'id': '1572734309519-939507600', 'offerItems': [{'services': [{'segments': [{'flightSegment': {'departure': {'iataCode': 'LOS', 'terminal': 'I', 'at': '2020-01-01T23:30:00+01:00'}, 'arrival': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-01-02T06:00:00+01:00'}, 'carrierCode': 'AF', 'number': '149', 'aircraft': {'code': '789'}, 'operating': {'carrierCode': 'AF', 'number': '149'}, 'duration': '0DT6H30M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'L', 'availability': 9, 'fareBasis': 'LLXSRNG'}}, {'flightSegment': {'departure': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-01-02T08:00:00+01:00'}, 'arrival': {'iataCode': 'JFK', 'terminal': '1', 'at': '2020-01-02T10:30:00-05:00'}, 'carrierCode': 'AF', 'number': '22', 'aircraft': {'code': '77W'}, 'operating': {'carrierCode': 'AF', 'number': '22'}, 'duration': '0DT8H30M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'L', 'availability': 9, 'fareBasis': 'LLXSRNG'}}]}, {'segments': [{'flightSegment': {'departure': {'iataCode': 'JFK', 'terminal': '1', 'at': '2020-02-08T18:40:00-05:00'}, 'arrival': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-02-09T08:00:00+01:00'}, 'carrierCode': 'AF', 'number': '7', 'aircraft': {'code': '77W'}, 'operating': {'carrierCode': 'AF', 'number': '7'}, 'duration': '0DT7H20M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'N', 'availability': 9, 'fareBasis': 'NLWSRNG'}}, {'flightSegment': {'departure': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-02-09T14:10:00+01:00'}, 'arrival': {'iataCode': 'LOS', 'terminal': 'I', 'at': '2020-02-09T20:30:00+01:00'}, 'carrierCode': 'AF', 'number': '104', 'aircraft': {'code': '332'}, 'operating': {'carrierCode': 'AF', 'number': '104'}, 'duration': '0DT6H20M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'N', 'availability': 9, 'fareBasis': 'NLWSRNG'}}]}], 'price': {'total': '1620.29', 'totalTaxes': '662.29'}, 'pricePerAdult': {'total': '1620.29', 'totalTaxes': '662.29'}}]} {% for … -
Logging status 500 errors to text file
I'd like to log status 500 errors that pop up on my server to a text file. I've implemented the below code in my settings file. Upon the first 500 error, a txt file was created in the directory I expected it to be in, but it's empty. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'logfile': { 'class': 'logging.handlers.WatchedFileHandler', 'filename': '/home/jasonhoward/webapps/django/myproject/errors.log' }, 'django': { 'handlers': ['logfile'], 'level': 'ERROR', 'propagate': False, } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, } } } Thanks for your help! -
Django "TypeError: '...' object is not iterable"
I need multiple values to be in the courses' contacts, for example phone, facebook etc. I'm overriding create method to make writable nested fields. Everything works fine with "branches". I'm confused because I can't get why Contact is not iterable. Models.py: class Branch(models.Model): latitude = models.CharField(max_length=50) longitude = models.CharField(max_length=50) address = models.CharField(max_length=100) class Meta: ordering = ['latitude'] def __str__(self): return self.address class Contact(models.Model): type = models.IntegerField(choices=TYPE, default=1) value = models.CharField(max_length=100, null=False) class Meta: ordering = ['type'] def __str__(self): return "{} {}".format(self.type, self.value) class Course(models.Model): ... branches = models.ForeignKey(Branch, on_delete=models.CASCADE, null=False, default=True) contacts = models.ForeignKey(Contact, on_delete=models.CASCADE, null=False, default=True) class Meta: ordering = ['name'] def __str__(self): return self.name Serializers.py: class CourseSerializer(serializers.ModelSerializer): ... branches = BranchSerializer(many=True) contacts = ContactSerializer(many=True) class Meta: model = Course fields = ['name', 'description', 'category', 'logo', 'contacts', 'branches'] def create(self, validated_data): branches_data = validated_data.pop('branches') contacts_data = validated_data.pop('contacts') course = Course.objects.create(**validated_data) for branches in branches_data: branch = Branch.objects.create(**branches) course.branches = branch for contacts in contacts_data: contact = Contact.objects.create(**contacts) course.contacts = contact return course -
pip install mysqlclient does'nt work on linux host
Now i upload my project into the linux host and install my packages with host terminal after this when i want runserver this error doesn't allow me for complete uploading when I run pip install mysqlclient this error show off : Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/mahdiade/virtualenv/portfolio/3.7/bin/python3.7_bin -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install- what's the problem? -
Attach Div to Th id / django forloop counter issue
I have a table that looks like this: {% for object in object_list %} <tr> {% for object in object_list %} <td id="destination">{{ forloop_counter }}</td> {% endfor %} </tr> {% endfor %} and I am using this function to attach the bar to the th. function MoveDiv() { var fragment = document.createDocumentFragment(); fragment.appendChild(document.getElementById('bar')); document.getElementById('destination').appendChild(fragment); } I wanted to use the foorloop counter to assign an id to each cell. But the forloop counter populates the cells of the same column with the same id. What else can I try to assign a unique id to each cell? Thank you -
Date does not conform to the required format
I am creating a form, and this form has a date that should be in the format "dd / mm / yyyy", but when I save the date in this format the following error appears: The specified value "11/02/2019" does not conform to the required format, "yyyy-MM-dd". models.py: class Example(models.Model) date = models.DateField(null=False, default=date.today) The form i'm calling in html: {% render_field form.date type="date" %} settings.py: DATE_INPUT_FORMATS = ['%d/%m/%Y'] LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I need the date to be in the format "dd / mm / yyyy", could someone help me? -
How can run django tests in Pycharm Pro, getting ImproperlyConfigured and AppRegistryNotReady errors
I am having issues running django tests in PyCharm Pro. I am able to run python manage.py runserver just fine. I am able to migrate, makemigrations, manage.py test just fine. Actually, everything with manage.py runs as expected. Whenever I run tests in PyCharm (by clicking the green run button), I get this error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have done several things to fix this: I have, in my test file, put this: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' (with mysite being the correct dir I promise) I have a settings file and a wsgi file, and my wsgi file does set the DJANGO_SETTINGS_MODULE: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() The only thing that has taken me out of this error was by setting up the configuration for that test class by going to Edit Configuations -> Environment -> Environment Variables and adding the DJANGO_SETTINGS_MODULE there. This only gets me a different error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Plus, I have to do this for every test class and I can't run individual tests in the class, but must rather run the entire … -
Django: How to automatically refresh page after session variable has changed?
I am rendering my nav bar using just html On my nav bar I am showing the number of items current in my shopping cart via request.session.cart_items where cart_items is my session variable When I add items to my cart my cart_items changes, and I see that indeed it has changed when I use print(request.session.cart_items) The problem is that my html only shows the updated request.session.cart_items when I refresh the page. How can I make the page refresh automatically once there has been a change to request.session.cart_items? Here is my navbar.html <nav class="main-nav"> <ul> <li> <a href="/">Painting Website</a> </li> <li> <a href="/">{{ request.session.cart_items}}</a> </li> </ul> </nav> Here is also my CartUpdateAPIView(APIView) from my views.py if that helps class CartUpdateAPIView(APIView): permission_classes = [permissions.AllowAny] def get(self, request, pk=None, *args, **kwargs): product_id = request.get('product_id') product_obj = Painting.objects.get(pk=product_id) cart_obj, new_obj= Cart.objects.new_or_get(request) #remove from cart if already in cart if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) #add to cart if not in cart already else: cart_obj.products.add(product_obj) #adding to many-to-many return redirect("cart-api:cart-list") def post(self, request, pk=None, *args, **kwargs): product_id = request.data['products'][0] #to make sure that product_id is actually coming through if product_id is not None: try: #getting an instance of the painting from the Painting model product_obj = … -
Django `ModuleNotFoundError: No module named 'config'` in Zeppelin notebook
I'm trying to run django.setup() inside Apache Zeppelin. Previously, I have done this successfully in both Jupyter and Zeppelin. Check my Python env. %python sys.executable '/Users/layne/.pyenv/versions/neurodb-py3.7/bin/python' Set my working directory. $ cd ~/Desktop/NeuroDB Make sure working directory is accessible. %python sys.path.append("/Users/layne/Desktop/NeuroDB") %python import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") django.setup() ERROR Traceback (most recent call last): File "/tmp/zeppelin_python-1811280867650127013.py", line 307, in <module> exec(code, _zcUserQueryNameSpace) File "<stdin>", line 4, in <module> File "/Users/layne/.pyenv/versions/neurodb-py3.7/lib/python3.7/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/layne/.pyenv/versions/neurodb-py3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/layne/.pyenv/versions/neurodb-py3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/layne/.pyenv/versions/neurodb-py3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/layne/.pyenv/versions/3.7.3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/zeppelin_python-1811280867650127013.py", line 319, in <module> raise Exception(traceback.format_exc()) Exception: Traceback (most recent call last): File "/tmp/zeppelin_python-1811280867650127013.py", line 307, in <module> … -
OperationalError at / no such table: blog_post_categories
I'm trying to add category section to my blog pet-project; I feel that I almost there, but on the last part of work it showed me an error: "OperationalError at / no such table: blog_post_categories" My models.py class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='posts') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=20) My views.py def home(request): content = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', content) def blog_category(request, category): posts = Post.objects.filter( categories__name__contains=category ).order_by( '-created_on' ) content = { 'category': category, 'posts': posts } return render(request, 'blog/blog_category.html') I don't really understand why, but debugger shows that it is something wrong in base.html on line 0 "In template /media/john/DATA/DJANGO/WORKING/blog/templates/blog/base.html, error at line 0" -
How to call a model's method before saving a serializer in Django Rest Framework?
I have a model where I am trying to create an object using DRF. The model class has a method which I would like to call before saving the serializer. Something like this: class MyModel(models.Model): ... def do_something(self): ... The serializer code: serializer = MyModelSerializer(data=request.data) serializer.obj.do_something() # Does not work serializer.save() Hopefully, you guys get the idea. -
Django: How to connect CheckboxSelectMultiple with an CharField or IntegerField
My question is how can I connect with each CheckboxSelectMultiple Item another Charfield or IntegerField? I have a typical code structure, a Model is used in a Form that is then saved in the views. class DocAideForm(forms.ModelForm): class Meta: model = DocAide fields = [..., 'drug', 'int_list'] widgets = { ..., 'drug': forms.CheckboxSelectMultiple() } In views.py I do it like this: if doc_aide_from.cleaned_data['drug']: p = Prescription(patient=patient) p.qty = doc_aide_from.cleaned_data['int_list'] p.save() p.drug.add(*list(doc_aide_from.cleaned_data['drug'])) This works fine but they are not connected with each Drug Item. I want the Drug to be shown in the template with the Qty Charfield or IntegerField in the same place. Like this for each Drug: x Paracetamol Qty: ___1____ How can that be accomplished.