Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid redirect after like in Django?
I've created likes logic by sending a post request to the specific url. Disadvantage of this method is that I can't avoid redirect. Even HTTPresponseRedirect to the current page is frustrating for user, cause it bangs viewport to the start of the page. I don't understand ajax, but wouldn't mind to use java script if needed. Most likely solution is to create it in Django somehow, but I think it might be impossible. So, any solutions are welcome! -
How to add google pay payment gateway with react?
Hello guys I am trying to integrate a payment gateway for my first e-commerce process build with react and Django as the backend. I tried with Razorpay but they halted onboarding new merchants. After watching some videos I found that we can add google pay also with react with the google pay react button. I found this package https://www.npmjs.com/package/@google-pay/button-reactto integrate payment, but it didn't show up option, just the card option and when I tried with the card in response it didn't show a proper response. it gives a token not a transaction or id as Razorpay or other payments give. Please guide me if anybody integrates payment with this library. -
DjangoChatbox Using WebSocket and Django Channels
Hey I Create a django chatbox using websocket while watching a tutorial In tutorial the websocket connection is working properly but in my project the websocket connection is not start it always shows close state..............please help me enter image description here Here is the error enter image description here second error consumer.py :_ import json from django.contrib.auth.models import User from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import Room, Message class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): data = json.loads(text_data) print(data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username })) @database_sync_to_async def save_message(self, username, room, message): user = User.objects.get(username=username) room = Room.objects.get(slug=room) Message.objects.create(user=user, room=room, content=message) routing.py :- from django.urls import path from . import consumers websocket_urlpatterns = … -
DRF How to overide the way objects are written to DB
I have a field in my model that contains a string. That string is given in plaintext when there is a create, patch or partial patch call to the API endpoint. But the value stored in the DB should be encrypted. But if there is a list or retrieve call, then the encrypted value should be displayed. Having the field as "write_only" is not an option as I need to retrieve the encrypted string via the API. So the problem is that I have to take the input value and encrypt before it gets stored on the DB. But when I retrieve the objects then the value should be displayed as it is stored in the DB. One solution I was thinking of was to use different serializers for the different methods in the Viewset and having a method field that encrypts the string. And a simple CharField to display the value in the other serializer. Another could be to change the object model itself to have the functionality build in the model. But maybe there is a better way to do it? -
Sum together list of F expressions
Is there a way to specify (in an annotation or aggregation) that a sequence of F expressions should be summed together without manually typing out F("first_prop") + F("second_prop") + ...? I want something similar to how python's sum() function allows you to pass an iterable and get the sum of the values in the iterable i.e. sum([1,2,3]) returns 6. Concretely, I want something that looks like this: class Tree(TimeStampedModel): leaf_count = models.IntegerField() branch_count = models.IntegerField() Tree.objects.create(leaf_count=60, branch_count=8) Tree.objects.create(leaf_count=30, branch_count=3) # now I want to annotate a combined count using my imaginary IterableSum aggregator combined_sums = list( Tree.objects.all().annotate( combined_count=IterableSum(fields=[F("leaf_count"), F("branch_count")]) ).values_list("combined_count", flat=True) ) combined_sums # [68, 33] How can I achieve this? -
Django query to combine two tables without aggregation
I want to write a django query and avoid raw sql doing the following: Lets imaging I have those two tables resulting from django query (query under the table): Table 1: Name Count First 4 Second 7 Third 2 Fourth 12 Fith 5 Query: q1 = Entity.objects.filter(some_condition=1)\ .values( "name", ).annotate(Count("name")) Table 2: Name Count First 13 Second 6 Third 2 Fourth 12 Sixth 3 Query: q2 = Entity.objects.filter(some_condition=2)\ .values( "name", ).annotate(Count("name")) What I want to achieve is the following table using just Django query: Name Count table 1 Count table 2 First 4 13 Second 7 6 Third 2 2 Fourth 12 12 Fith 5 0 Sixth 0 3 Two solutions seems to solve it but didn't work. If I use 3 = (q1 | q2) the column "count" will be aggregated and there will be just one count column. If I'm using q1.union(q2) I get the error message: django.db.utils.DatabaseError: ORDER BY not allowed in subqueries of compound statements. -
Cannot login to Django admin by `Apache/mod_wsgi` but it worked normally by `python runserver`
Everything of my django project is OK when I accessed to it by running python runserver. But if I accessed to my django project remotely via Apache/mod_wsgi, I cannot login with valid passwd, like the picture below: That error occured after my env being re-established because of my python updating. Here is my env list: aldryn-apphooks-config==0.6.0 asgiref==3.6.0 click==7.1.2 cmsplugin-polls==0.1.0 defusedxml==0.6.0 diff-match-patch==20200713 dj-database-url==0.5.0 Django==3.1.7 django-admin-ip-restrictor==2.2.0 django-appdata==0.3.2 django-awesomplete==0.2.1 django-bootstrap3==14.2.0 django-classy-tags==2.0.0 django-cms==3.7.4 django-cors-headers==3.6.0 django-crispy-forms==1.10.0 django-filer==2.0.2 django-formtools==2.2 django-import-export==2.4.0 django-ipware==3.0.2 django-js-asset==1.2.2 django-jsonfield==1.4.1 django-markdownx==3.0.1 django-mdeditor==0.1.18 django-meta==2.0.0 django-mptt==0.11.0 django-parler==2.2 django-polymorphic==3.0.0 django-reversion==3.0.8 django-sekizai==2.0.0 django-sortedm2m==3.0.2 django-tagging==0.5.0 django-tagging-autocomplete==0.5.1 django-taggit==1.4.0 django-taggit-autosuggest==0.3.8 django-taggit-templatetags==0.2.5 django-templatetag-sugar==1.0 django-treebeard==4.3.1 djangocms-admin-style==1.5.0 djangocms-apphook-setup==0.4.1 djangocms-attributes-field==2.0.0 djangocms-blog==1.2.3 djangocms-bootstrap4==1.6.0 djangocms-file==2.4.0 djangocms-googlemap==1.4.0 djangocms-icon==1.5.0 djangocms-installer==1.2.3 djangocms-link==2.6.1 djangocms-picture==2.4.0 djangocms-snippet==2.3.0 djangocms-style==2.3.0 djangocms-text-ckeditor==3.10.0 djangocms-video==2.3.0 djangorestframework==3.12.2 easy-thumbnails==2.7 et-xmlfile==1.0.1 future==0.18.2 html5lib==1.1 httplib2==0.9.2 jdcal==1.4.1 jieba==0.42.1 joblib==1.0.0 lxml==4.9.2 Markdown==3.3.3 MarkupPy==1.14 nltk==3.5 odfpy==1.4.1 openpyxl==3.0.5 Pillow==7.2.0 psycopg2==2.8.6 pytz==2020.1 PyYAML==5.3.1 regex==2020.11.13 six==1.15.0 sqlparse==0.3.1 tablib==3.0.0 tqdm==4.55.0 tzlocal==2.1 Unidecode==1.1.1 webencodings==0.5.1 Whoosh==2.7.4 xlrd==2.0.1 xlwt==1.3.0 I had tried to adjust some cache settings in settings.py according to django FAQ, but nothing helps. CSRF_COOKIE_SECURE= False SESSION_COOKIE_SECURE= False SESSION_COOKIE_DOMAIN= "159.226.116.202" -
Django Forms: Django-select2 Not rendering multi select box correctly
Im using django-select2 : https://django-select2.readthedocs.io/en/latest/index.html Im attempting to create a multiple tag select dropdown box similar to this: [![MultiSelectTagBox][1]][1] The problem is its not loading as expected: [![Actual Rendering of Form][2]][2] Below is my code. Im using the Select2TagWidget currently but I have tried the following other widgets: ModelSelect2MultipleWidget Select2MultipleWidget forms.py class BankForm(ModelForm): required_css_class = "required" formField1 = forms.ModelMultipleChoiceField( queryset=Bank.objects.all(), label="Lead Bank", widget=Select2TagWidget, ) class Meta: model = AdditionalBank fields = [ "formField1", ] """ Labels for the fields we didn't override """ labels = {} urls.py Ive added the correct path to my urls.py file path("select2/", include("django_select2.urls")), I have the redis queue setup correctly in my settings.py file. Im pretty confident the rest of the configuration is setup correctly outlined in the docs for django-select2 My Front end form is rendering this html/css: <select name="lead\_bank" lang="None" data-minimum-input-length="1" data-theme="default" data-allow-clear="false" data-tags="true" data-token-separators="\[\&quot;,\&quot;, \&quot; \&quot;\]" required="" id="id\_lead\_bank" class="django-select2" multiple=""> <option value="1">Citi</option> <option value="2" selected="">USBank</option> <option value="3">Wells Fargo</option> <option value="4" selected="">NY Bank</option> </select> [1]: https://i.stack.imgur.com/15ij6.png [2]: https://i.stack.imgur.com/YPDMS.png Keep in mind I am very new to front end dev. Primarily a backend dev. Thank you in advance ! -
Django OuterRef access grandparent
I've this piece of code parent_product_subquery = Count(Subquery(Product.objects.filter( Q(Q(description__id__in=[OuterRef('pk')]) | Q(productvariant__name__id__in = [OuterRef('pk')])), user=self.request.user, **filter_kwargs, ).only('pk'))) obj = get_object_or_404(Translation.objects.annotate(is_user_owner=parent_product_subquery), pk=self.kwargs['translation_id']) print(obj.is_user_owner) if obj.is_user_owner: return obj it always prints False, what am I doing wrong? -
Pass "next" url in Django from login page to signup page
For one of form view, I use LoginRequiredMixin and when a user is not logged in and it redirects to the login page with parameters "/login/?next=/foo/bar/". There is a signup link below the page for those who don't have an account. I want to have such link to signup that I want it to have the parameters "/signup/next=/foo/bar/". I don't know how to include the parameters in {% url %} tag. How can I make it possible? Answers in Class Based Views please. -
In Django, how to check if user is in site_id (site_id are created by after)
the objective of the system is to check if the user is in such site_id or not to display a part of the html page to him here I do it with groups : views.py def is_admin(user): return user.groups.filter(id=1).exists() def is_client(user): return user.groups.filter(id=4).exists() template (main_list.html) {% for group in request.user.groups.all %} {% if 1 == group.id %} and I would like to do it with my site_id (Foreign Key) here is my first attempt : views.py def is_siteone(user): return user.site_id.filter(id=1).exists() template (main_list.html) {% if is_siteone %} models.py class Site(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=255) version = models.CharField(verbose_name='Program version', blank=False, default='1.0', max_length=20) def __str__(self): return self.name def filter(self, id): pass but it returns the following error error return Do you have any ideas on how to proceed? My site_id is a Foreign key of a Site table in table auth_user of Django -
Django How to make the transition from one post to another and back
There is a model and posts attached to it. I can not figure out how to make the transition from one post to the next and back. I read many articles, but I did not find a suitable one for myself. Here is my code. How can this be done? Where did I make a mistake and how can I fix it? http://127.0.0.1:8000/seasons/season-1/episode-2 NoReverseMatch at /seasons/season-1/episode-2 NoReverseMatch at Reverse for 'episode-detail' with arguments '('', 'episode-1')' not found. 1 pattern(s) tried: ['seasons/(?P<seasonpost_slug>[-a-zA-Z0-9_]+)/(?P<episodepost_slug>[-a-zA-Z0-9_]+)\Z'] Error during template rendering previous return render(request, 'content/episode.html', { … Local vars current_episode <episode: episode-2> episodepost <QuerySet [<episode: episode-2>]> episodepost_slug 'episode-2' next_episode <episode: episode-3> previous_episode <episode: episode-1> request <WSGIRequest: GET '/seasons/season-1/episode-2'> seasonpost_slug 'season-1' class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) Views def ContentHome(request): homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/home.html',{ 'season_menu':season_menu, 'home':homepages, 'season':seasonpages}) def ContentSeasons(request): seasonspages=seasons.objects.all() homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/seasons.html',{ 'season_menu':season_menu, 'home':homepages, 'seasons':seasonspages, 'season':seasonpages}) def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) … -
has_perm method gives False even if user has pemission
I added permission <Permission: blog | post | Can add post> to a user vía shell. It worked because in admin site it is added. Nevertheless when I run below methods in a shell it shows no permission was added. user2.get_user_permissions() -> set() user2.has_perm('blog.add_post') -> False -
How to change the id in django template of a ModelMultipleChoiceField form
i have a django form with ModelMultipleChoiceField <div class="form-group"> {{ form.contracts|as_crispy_field }} </div> For example, i have 4 contract instances in django. In django template the ids for the contracts are rendered: id=id_contracts_0 id=id_contracts_1 id=id_contracts_2 id=id_contracts_3 Now i want to set the checkbox to true if criteria is True. In template iam getting a dictionary {"id", 67} from a calendar. What is want? I want to change the id of the contracts in template, for exameple i want to change the id= id_contracts_3 to the value of the dictionary so, id=id_contracts_67 This has to be done in the template, so jquery of javascript. -
Validation errors when trying to unlink a related model in Django admin inline?
In my Django project I have the following models: TreatUser, Customer and Stakeholder: from django.db import models class UserType(models.Model): name = models.CharField(max_length=20) class Meta: app_label = 'users' def __str__(self): return self.name def __repr__(self): return self.name class TreatUser(AbstractUser): # remove the username from our model username = None email = models.EmailField(unique=True) user_type = models.ForeignKey( UserType, on_delete=models.CASCADE, related_name='users', ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = TreatUserManager() class Meta: app_label = 'users' def __str__(self): return self.email def __repr__(self): return self.email class Stakeholder(models.Model): stakeholder_id = models.CharField(max_length=50, unique=True) user = models.OneToOneField( TreatUser, on_delete=models.CASCADE, ) class Meta: app_label = 'users' def __str__(self): return self.user.email def __repr__(self): return self.user.email class Customer(models.Model): user = models.OneToOneField( TreatUser, on_delete=models.CASCADE, ) stakeholder = models.ForeignKey( Stakeholder, on_delete=models.SET_NULL, related_name='customers', null=True, blank=True, ) class Meta: app_label = 'users' def __str__(self): return self.user.email def __repr__(self): return self.user.email I have an apparently a super-easy scenario for my models workflow: Stakeholder and Customer should be linked to only one TreatUser; Multiple Customers can be linked to the same Stakeholder; I've created the admin models for the above as follows: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from users.models import TreatUser, UserType, Stakeholder, Customer @admin.register(TreatUser) class TreatUserAdmin(UserAdmin): list_display = ('email', 'user_type', 'is_staff', 'is_active',) list_filter = … -
How to retrieve data from an SQL database stored in Azure with a Django WebApp (both in the same Azure resource group)?
I am trying to develop a WebApp for my company where the users can visualize data that is stored in an SQL SERVER database in Azure using a Django webapp. I have been using pyodbc in the past to send the queries and retrieve the required data but was wondering if there was a better way like adding a REST API to the SQL DB or directly setting the DB as part of the Django databases. Both the Django WebApp and the SQL DB are in the same Azure resource group. Thanks for your help. -
Cannot use 'git push' on pythonanywhere fatal: Authentication failed for 'https://github.com/yashtank09/mystie.git/'
After using this command. git push I having error like this in my pythonanywhere console: remote: Support for password authentication was removed on August 13, 2021. remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication. fatal: Authentication failed for 'https://github.com/yashtank09/mystie.git/' -
Get response from PayPal buttton in django
I have integrated PayPal buttons into my project. I am sharing my code here for PayPal Buttons. <script src="https://www.paypal.com/sdk/js?client-id=MyClientID&currency=USD" data-sdk-integration-source="button-factory"></script> <script> function initPayPalButton() { paypal .Buttons({ style: { shape: "rect", color: "blue", layout: "horizontal", label: "buynow", }, createOrder: function (data, actions) { return actions.order.create({ purchase_units: [{amount: {currency_code: "USD", value: totalAmount}}], }); }, onApprove: function (data, actions) { return actions.order.capture().then(function (orderData) { // Full available details console.log("Capture result", orderData, JSON.stringify(orderData, null, 2)); // Show a success message within this page, e.g. const element = document.getElementById("paypal-button-container"); element.innerHTML = ""; element.innerHTML = "<h3>Thank you for your payment!</h3>"; // Or go to another URL: actions.redirect('thank_you.html'); }); }, onError: function (err) { console.log(err); }, }) .render("#paypal-button-container"); } initPayPalButton(); </script> <div class="paypalButton-mainDiv"> <div id="smart-button-container"> <div style="text-align: center"> <div id="paypal-button-container"></div> </div> </div> </div> But I am not able to get the response back from this code after Payment. I need to get the response and want to store it in my database. -
Django Reverse for '...' with arguments '('', '...')' not found. 1 pattern(s) tried:
Help is needed. I have tried many solutions, but nothing works. Always one mistake. Please help me solve the problem. http://127.0.0.1:8000/seasons/season-1/episode-2 NoReverseMatch at Reverse for 'episode-detail' with arguments '('', 'episode-1')' not found. 1 pattern(s) tried: ['seasons/(?P<seasonpost_slug>[-a-zA-Z0-9_]+)/(?P<episodepost_slug>[-a-zA-Z0-9_]+)\Z'] Error during template rendering previous return render(request, 'content/episode.html', { … Local vars current_episode <episode: episode-2> episodepost <QuerySet [<episode: episode-2>]> episodepost_slug 'episode-2' next_episode <episode: episode-3> previous_episode <episode: episode-1> request <WSGIRequest: GET '/seasons/season-1/episode-2'> seasonpost_slug 'season-1' class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) Views def ContentHome(request): homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/home.html',{ 'season_menu':season_menu, 'home':homepages, 'season':seasonpages}) def ContentSeasons(request): seasonspages=seasons.objects.all() homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/seasons.html',{ 'season_menu':season_menu, 'home':homepages, 'seasons':seasonspages, 'season':seasonpages}) def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) return render(request, 'content/season.html',{ 'home':homepages, 'seasons':seasonspages, 'season':seasonpages, 'season_menu':season_menu, 'episode': episodepost,}) def ContentEpisode(request, seasonpost_slug, episodepost_slug): episodepost = episode.objects.filter(slug=episodepost_slug, cat__slug=seasonpost_slug) current_episode = get_object_or_404(episodepost, slug=episodepost_slug, cat__slug=seasonpost_slug) previous_episode = episode.objects.filter(cat__slug=seasonpost_slug, pk__lt=current_episode.pk).first() next_episode = episode.objects.filter(cat__slug=seasonpost_slug, pk__gt=current_episode.pk).first() return render(request, 'content/episode.html', { 'episode': episodepost, 'current_episode': current_episode, 'previous_episode': previous_episode, 'next_episode': next_episode, }) path('', views.ContentHome, … -
Django Test - Not working in GitHub actions
I have 2 Django tests that are working perfectly fine locally but it fails on GitHub actions, this is the code: Models class Empresa(models.Model): name = models.CharField(max_length=120, verbose_name='Razon Social') cuit = models.CharField(max_length=11, validators=[MinLengthValidator(11)]) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.user: user = get_current_user() if user and not user.pk: user = None if not self.pk: self.user = user self.user = user return super().save(force_insert, force_update, using, update_fields) def toJSON(self): item = model_to_dict(self) return item And I try to test: Creation successfully of Empresa -> It works ok Error on creation because of a long name -> It works locally but not on GitHub actions Error on creation because of a long cuit-> It works locally but not on GitHub actions This is the test: class EmpresaTesting(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create(username='testuser', password='12345') self.user.save() def test_create_empresa_ok(self): this_empresa = Empresa.objects.create(name='Empresa 1', cuit='30999999991', user=self.user) self.assertTrue(isinstance(this_empresa, Empresa)) self.assertEqual(str(this_empresa), 'Empresa 1') def test_create_empresa_long_name(self): long_name = "a" * 121 with self.assertRaisesMessage(DataError, "Data too long for column 'name' at row 1"): Empresa.objects.create(name=long_name, cuit='30999999991', user=self.user) def test_create_empresa_long_cuit(self): with self.assertRaisesMessage(DataError, "Data too long for column 'cuit' at row 1"): Empresa.objects.create(name="Empresa … -
how to insert additional model without losing data stored on mysql
My django app has two model, for example model_A and model_B, and this app could run well on docker. The docker compose is following version: '3.8' services: app: build: ...... volumes: ..... db: image:mysql5.7 volume: ....... nginx: image:.... volumes: volume_mysql: ....... After running the app for a while, I want to add a model, for example model_C on the app, exchanging app container to new one containing model_C. docker-compose stop docker rm app docker rmi app docker-compose up -d --build And makemigrations/migrate process also work without any error message docker exec app python manage.py makemigrations docker exec app python manage.py migrate On the other hand, I did not update the volume_mysql, because volume_mysql contained a lot of important data (I was reluctant to remove the volume, which resulted in loose all data) When I tried accessing model_c (on admin page), however, error_message 1146, "Table 'race_record.result_model_C' doesn't exist" was displayed. I guess it seem to be because volume_mysql is old, having yet to conntain ‘model_c’, although migrate process was done well. So, how to add model_c without losing date stored on mysql -
Add an item with multiple variations to basket in Django
I have a views.py and contexts.py that adds a product with a particular flavour to the basket on my Django site. I have copied this logic from a course I'm on. I now want to be able to have multiple variations on products and add them to my basket. For instance a strength as well as a flavour. Here is my add_product view: def add_to_basket(request, item_id): """ Add a quantity of the specified product to the shopping basket """ product = get_object_or_404(Product, pk=item_id) quantity = int(request.POST.get('quantity')) redirect_url = request.POST.get('redirect_url') flavour = None if 'product_flavour' in request.POST: flavour = request.POST['product_flavour'] strength = None if 'product_strength' in request.POST: strength = request.POST['product_strength'] basket = request.session.get('basket', {}) if flavour: if item_id in list(basket.keys()): if flavour in basket[item_id]['items_by_flavour'].keys(): basket[item_id]['items_by_flavour'][flavour] += quantity messages.success(request, f'Updated {product.name} flavour {flavour.upper()} quantity to {basket[item_id]["items_by_flavour"][flavour]}') else: basket[item_id]['items_by_flavour'][flavour] = quantity messages.success(request, f'Added {product.name} flavour {flavour.upper()} to your basket') else: basket[item_id] = {'items_by_flavour': {flavour: quantity}} messages.success(request, f'Added {product.name} flavour {flavour.upper()} to your basket') else: if item_id in list(basket.keys()): basket[item_id] += quantity messages.success(request, f'Updated {product.name} quantity to {basket[item_id]}') else: basket[item_id] = quantity messages.success(request, f'Added {product.name} to your basket') request.session['basket'] = basket return redirect(redirect_url) Here is my contexts.py that gets back the contents of the … -
How i can upload multiple images in django?
I can't figure out how to upload more than one image in django. models.py : def get_upload_path(self, filename): if isinstance(self, UserProfile): return f'members/{self.user.username}/avatars/{filename}' elif isinstance(self, Apartment): return f'members/{self.author.username}/apartment_pics/{filename}' else: return None class Apartment(models.Model): #---fields---# images = models.ManyToManyField('Image', blank=True) class Image(models.Model): image = models.ImageField(upload_to=get_upload_path) def __str__(self): return self.image.name also the forms.py class ApartmentForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta: model = Apartment fields = ('image',) views.py class ApartmentCreateView(CreateView): model = Apartment form_class = ApartmentForm template_name = 'post_a_room.html' success_url = reverse_lazy('home') def form_valid(self, form): form.instance.author = self.request.user response = super().form_valid(form) for image in self.request.FILES.getlist('images'): Image.objects.create(image=image, apartment=self.object) return response and html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="id_images">Images</label> <input type="file" name="images" id="id_images" class="multifilefield form-control" multiple> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> this method allows me to select more files but it crashes when i hit submit, i get an error : expected str, bytes or os.PathLike object, not NoneType -
How to connect databricks delta tables from Django application
I am new to Django framework, in my project I have requirement that I have to connect to databricks delta tables and perform CRUD operation on it. If we can connect it. I request you to list down the steps please.Thanks. -
Efficient way to continuously consume messages from Redis Streams while being connected to Websockets through Django Channels
I have written a Django application to receive updates of long running tasks. I am using Redis as a channel layer for web-sockets and also making use of Redis Streams to store the updates of the tasks that are currently running. I have spawned a thread from connect method of WebSocket Consumer to run an infinite loop to continuously check for updates from Redis Consumer. This seems to be a hackish solution for what I am trying to achieve i.e. to remain connected to the websocket and also simultaneously receive updates from Redis Streams. This is my code for Websocket Consumer. As you can see, I am running an infinite loop to check for any new messages in the stream through Redis Consumer. import json from threading import Thread from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from django.utils import timezone from redis import ConnectionPool, Redis from redis_streams.consumer import Consumer class ProgressStateConsumer(WebsocketConsumer): def __init__(self): self.task_id = self.task_group_name = None connection_pool = ConnectionPool( host="localhost", port=6379, db=0, decode_responses=True, ) self.redis_connection = Redis(connection_pool=connection_pool) self.messages = [] super().__init__() def connect(self): task_id = self.scope["url_route"]["kwargs"]["task_id"] self.task_id = task_id self.stream = f"task:{self.task_id}" self.task_group_name = ( f"task-{self.task_id}-{round(timezone.now().timestamp())}" ) async_to_sync(self.channel_layer.group_add)( self.task_group_name, self.channel_name ) thread = Thread(target=self.send_status) thread.start() self.accept() def …