Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass the same randomly generated list to both POST and GET views in python/django
I'm developing a quiz app which pulls a random subset of 3 questions the queryset Trivia. I can generate the random subset without issue and display 3 multiple choice questions. But when the user makes selections and submits, the trivia view generates a new random subset. Thus, user answers are then compared to correct answers of a new random subset rather than the initial subset that the user viewed. How can I create this random subset and use it in both the GET and POST methods of my view? That is, I want the queryset "trivia" to be identical in both GET and POST methods. Ideas? def trivia(request): trivia_id_list = Trivia.objects.values_list('id', flat=True) random_trivia_id_list = random.sample(list(trivia_id_list), min(len(trivia_id_list),3)) trivia = Trivia.objects.filter(id__in=random_trivia_id_list) if request.method == 'POST': correct = 0 incorrect = 0 total = 0 for t in trivia: print(request.POST.get(t.question)) print(t.answer) print() if t.answer == request.POST.get(t.question): correct = correct + 1 else: incorrect = incorrect + 1 total = total + 1 result = correct/total return render(request, 'ColdBlooded/result.html', { "Incorrect": incorrect, "Correct": correct, "Total": total, "Trivia": trivia, "Result": result, }) else: return render(request, "ColdBlooded/trivia.html", { "Trivia": trivia }) -
django DeleteView - how to pass a parameter to use for success_url?
I am using a DeleteView where the I want to the success_url to be the view that called the DeleteView. This success_url requires two parameters to be passed to it. urls.py path('listparts/<uuid:company_pk>/<uuid:worker_pk>/', views.listparts, name='listparts'), path('deletepart/<uuid:part_pk>/', views.PartDeleteView.as_view(), name='deletepart'), view def listparts(request, company_pk, worker_pk): ... ... class PartDeleteView(DeleteView): model: Part success_url = reverse_lazy('listparts' company_pk worker_pk) partslist template <a href="{% url 'deletepart' part_pk %}">Delete this part</a> How do I pass company_pk and worker_pk to the DeleteView? I think the href becomes <a href="{% url 'deletepart' part_pk company_pk worker_pk %}">Delete this part</a> But I don't know how to deal with that in the DeleteView. I'm sure it has to do with dealing with kwargs but I'm still learning on how kwargs work in something like def get_success_url(self) -
Customize viewset to get an item id combine of slug and uuid Django Rest Framework
I want to get each single item from my database by a id combine of slug and uuid. In my model I have: class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(max_length=250, unique_for_date='published') name = models.CharField(max_length=250) def get_absolute_url(self): return reverse('name-of-the-view', kwargs={'uuid': self.id, 'slug': self.slug}) In my view I am using ModelViewSet: class ProductList(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer def get_object(self, queryset=None, **kwargs): item = self.kwargs.get('pk') return generics.get_object_or_404(Product, id=item) def get_queryset(self): return Product.objects.all() In my urls I am using router: from rest_framework.routers import DefaultRouter from .views import ProductList app_name = 'products' router = DefaultRouter() router.register('', ProductList, basename='product') urlpatterns = router.urls How can I customize it so I can get not just the self.kwargs.get('pk') but also the slug from the link. I mean that I want to have links to each iteam like this: "item-name-25b6e133" and "item-name-11ac4431", where the first part is the slug and the second is the uuid. The slug should be automatically created of name field by the POST request. Using path it would look like this: urlpatterns = [ path('<slug:slug>-<uuid:uuid>/', some_view, name='name-of-the-view'), ] -
upload 10000's of images to github?
I have created a server using the Django framework in python and it has more than 1000 photos, should I upload all of them to the git hub, as I want to upload the server and its data. -
Redis Server inside Docker Container with nginx + redis_pass
I'm developing a simple Chat application (based on django-private-chat2 ) with django & django-channels. I want the application to be fully Containerized and use nginx for routing inside the container. So I'm trying to connect through a web-socket to a redis-server running inside a docker container. I've tried many things (see below) but still can't get it to work. It is not unlikely that my general approach is wrong. Here is what I've got so far. Redis-Server and websocket connection works outside Docker container. Inside the docker container I compile and run nginx with the 'HTTP Redis' here this module is loaded via 'load_module *.so' inside nginx.conf, I've verified that the module is loaded. I've configured the redis-server inside the Docker-container to use 'bind 0.0.0.0 and protected-mode no' Inside nginx then I route all the '/' traffic to a django application running on port 8000. I route all traffic to 'chat_ws/' ( from the web socket ) to 127.0.0.1:6379 the redis-server ( with nginx reverse_proxy ). I've verified that routing works properly ( return 404 with nginx on chat_ws addresses works ) I can connect to the redis-server through redis-cli on my machine, when I use 'redis-cli -h DOCKER_CONTAINER_IP' so … -
Django and MongoDB - how to debug database error for password reset email?
I've connected my Django app with MongoDB, register/login/logout are all working fine. But when I use the Django default password reset email it throws a database error. url.py path('pw_reset/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('pw_done/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('pw_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('pw_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), I was able to land on the Django password reset page, but when I hit confirm it return the error DatabaseError at /pw_reset/ No exception message supplied -
Access to XMLHttpRequest response to preflight request doesn't pass access control check
I am trying to upload file using FilePond (with Svelte) to Google Storage signed URL. When Chrome is making preflight it gets 200, but than it seams not to get Access-Control-Allow-Origin header on this response. There is an error in JS console: Access to XMLHttpRequest at 'https://storage.googleapis.com/...' from origin 'https://***.appspot.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I generate signed URL in Python: bucket = storage_client.bucket(settings.PRIVATE_GCP_BUCKET) blob = bucket.blob(f'upload/video_{obj.id}.mp4') # Get the time in UTC ini_time_for_now = datetime.now(timezone.utc) # Set the expiration time expiration_time = ini_time_for_now + timedelta(minutes=15) signed_url = blob.generate_signed_url(expiration=expiration_time, method='POST', version='v4') this works and URL is returned to JS client, properly set on FilePond configuration. My CORS config is: [ { "origin": [ "https://***.appspot.com" ], "method": [ "GET", "PUT", "POST" ], "responseHeader": [ "Content-Type", "Content-Length", "Access-Control-Allow-Origin", "x-goog-resumable" ], "maxAgeSeconds": 604800 } ] I tried multiple variations of headers etc. How to properly setup my bucket to allow to upload file? Is this GCP bucket configuration mistake or something else is wrong? I tried passing as well content_type='application/octet-stream', to generate_signed_url. -
Django app using Graphql and Channels package throws Exception inside application: 'NoneType' object has no attribute 'replace'
I've got a Django app that uses graphene to implement GraphQL and I've got everything setup and working but I now have an error in the console which has popped up suddenly and although it doesn't break anything, at least from as far as what I can tell, it does keep showing up in the console and I'd like to fix it. I'm quite new to Django so I'm not able to figure out where this is coming from. It looks like it's coming from the channels package. This is the error in its entirety that happens immediately after the server runs and then again after every request is made. Django version 3.2.3, using settings 'shuddhi.settings' Starting ASGI/Channels version 3.0.3 development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. WebSocket HANDSHAKING /graphql/ [172.28.0.1:60078] Exception inside application: 'NoneType' object has no attribute 'replace' Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/security/websocket.py", line 35, in __call__ if self.valid_origin(parsed_origin): File "/usr/local/lib/python3.8/site-packages/channels/security/websocket.py", line 54, in valid_origin return self.validate_origin(parsed_origin) File "/usr/local/lib/python3.8/site-packages/channels/security/websocket.py", line 73, in validate_origin return any( File "/usr/local/lib/python3.8/site-packages/channels/security/websocket.py", line 74, in <genexpr> pattern … -
Why is Entry.objects.filter returning an empty query
I am reading an article on django about making queries over here. I have the following snippets. >>> Entry.objects.first().pub_date datetime.date(2021, 8, 18) >>> Entry.objects.first().mod_date datetime.date(2021, 8, 18) But if I try the following I get an empty queryset. Entry.objects.filter(pub_date__year=F('mod_date__year')) Why is it not working. Is this a bug? -
How to move files into another directory django-storage s3
I'm working on a news blog where you can add as many files to news as you want. For files storing properties, I'm using amazon s3 and django-strorage. But after I've added news-update view, I got some problems with files management. As you can see, here my files model class FileStorage(models.Model): file = models.FileField(upload_to=uploadFile) upload_path = models.TextField(blank=True, default='files/') def __str__(self): return f'Файл: {self.file.name.split("/")[-1]}' The main problem is how to update FileField after moving the file into another directory? Here is my files moving script. bucket = S3Boto3Storage() from_path = bucket._normalize_name(bucket._clean_name(self.instance.file.name)) to_path = bucket._normalize_name(bucket._clean_name(self.cleaned_data['upload_path'])) result = bucket.connection.meta.client.copy_object( Bucket=bucket.bucket_name, CopySource=bucket.bucket_name + "/" + from_path, Key=to_path) bucket.delete(from_path) All works good, but only with path. File in FileField store old path. How can I update it to? Screen with problem -
Unable to add/identify select_related with in django codebase
This is my views.py apparently named here as admin.py class BaseMembershipInline(ReadOnlyMixin, admin.TabularInline): class MembershipInlineFormSet(BaseInlineFormSet): def get_queryset(self): print("(((((((((((GET Q SET)))))))))))))))") # Orders by property field super().get_queryset() self._queryset = sorted( super().get_queryset(), key=lambda membership: membership.order ) return self._queryset model = Membership formset = MembershipInlineFormSet print("FORMSET ", formset) extra = 0 @classmethod def get_current_membership_ids(cls): # TODO Does this SELECT all accounts? print("))))))))GET OWNER((((((((((((") return Account.objects.all().values_list("current_membership_id") def change(self, obj): print("_____CHANGE ____________") # add custom redirect url to redirect admin to membership tab of account # detail page change_membership_url = reverse( "admin:accounts_membership_change", args=[obj.id] ) redirect_url = ( reverse("admin:accounts_account_change", args=[obj.account_id]) + "#tabs-2" ) link_url = change_membership_url + f"?{REDIRECT_FIELD_NAME}={redirect_url}" return format_html('<a href="{}">{}</a>', link_url, "Change") This is my models.py class Membership(AbstractBaseModel): # Billing frequency choices BILLING_FREQUENCY_MONTHLY = "monthly" BILLING_FREQUENCY_YEARLY = "yearly" BILLING_FREQUENCY_ONCE = "once" BILLING_FREQUENCY_NEVER = "never" BILLING_FREQUENCY_CHOICES = [ (BILLING_FREQUENCY_MONTHLY, "Monthly"), (BILLING_FREQUENCY_ONCE, "Once"), (BILLING_FREQUENCY_NEVER, "Never"), (BILLING_FREQUENCY_YEARLY, "Yearly"), ] # All database fields account = models.ForeignKey( "Account", related_name="memberships", on_delete=models.CASCADE ) plan = models.ForeignKey( "MembershipPlan", related_name="memberships", on_delete=models.PROTECT ) next_membership = models.OneToOneField( "self", related_name="previous_membership", null=True, blank=True, on_delete=models.DO_NOTHING, ) This is the inherited class for every model in my models.py class AbstractBaseModel(LogEntryMixin, models.Model): id = models.BigIntegerField( primary_key=True, default=generate_unique_id, editable=False ) creation_datetime = models.DateTimeField(auto_now_add=True, editable=False) update_datetime = models.DateTimeField(auto_now=True) objects = BaseModelManager() class Meta: … -
Blog Comments System with Class Based View in Django
Here is the function-based view that I have and it works fine: def PostDetailView(request, slug): post = Post.objects.get(slug = slug) comments = post.comment_set.all() new_comment = None if request.method == 'POST': form = CommentCreateForm(request.POST) if form.is_valid(): new_comment = form.save(commit = False) new_comment.post = post new_comment.save() else: form = CommentCreateForm() context = {'post': post, 'comments': comments, 'form': form, 'new_comment': new_comment} return render(request, 'blog/post-detail.html', context) I am trying to convert this to a class-based view as per: class PostDetailView(FormMixin, DetailView): model = Post template_name = 'blog/post-detail.html' form_class = CommentCreateForm new_comment = None def get_success_url(self): return reverse('post_detail', kwargs={'slug': self.object.slug}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = self.object.comment_set.all() context['form'] = self.get_form() context['new_comment'] = self.new_comment return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.post = self.object form.save() self.new_comment = True return redirect(self.object.get_absolute_url()) The template looks like this: <h1>{{post.title}}</h1> {{post.body|linebreaks}} {% with comments.count as total_comments %} <h2>{{ total_comments}} comment{{total_comments|pluralize}}</h2> {% endwith %} {% for comment in comments %} <div class="comment"> <p class="info"> Comment {{forloop.counter}} by {{comment.name}} {{comment.created}} </p> {{comment.body|linebreaks}} </div> {% empty %} <p>There are no comments yet.</p> {% endfor %} {% if new_comment %} <h2>Your comment has been added.</h2> {% … -
How to deal with double foreign keys in Django while creating an API?
I created these models for my database. It's supposed to be kind of a tree (country>multiple cities>multiple airports). The problem is I want to use autocomplete which would show not only the name of an airport and the name of the city, but also the name of the country. I'm stuck because I don't know how to add the country to my API (together with airports of course). Is there a way to do it or maybe I should change the architecture of my database? class Country(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=120) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.name class Airport(models.Model): name = models.CharField(max_length=150) abbr = models.CharField(max_length=4) city = models.ForeignKey(City, on_delete=models.CASCADE) country = city.country #how can I do this? def __str__(self): return self.name + ' (' + self.abbr + ')' from serializers.py: class AirportSerializer(serializers.ModelSerializer): city = serializers.StringRelatedField() class Meta: model = Airport fields = ['name', 'city'] from views - creating custom search API: class AirportList(generics.ListAPIView): serializer_class =AirportSerializer def get_queryset(self): airport = self.kwargs['airport'] list_airports = Airport.objects.filter(name__icontains = airport) return list_airports Path in case it's helpful: re_path('^airports/(?P<airport>.+)/$', views.AirportList.as_view()), script for autocomplete: <script> new Autocomplete ('#autocomplete', { search: input=>{ console.log(input) const url = `/airports/${input}/` return … -
Python not modifying global variable
i have below code failure = "" def walk(dictItems): returnVal = "" for key, item in dictItems.items(): if isinstance(item,dict): walk(item) else: returnVal = returnVal +"<li>"+key+" : "+ item + "</li>" global failure failure = returnVal walk(dictItems) print(failure) failure variable is always null despite having vaulues on returningVal any help? -
Django, multiple DB hits when repeating one related query
This is the model: class Category(models.Model): name = models.TextField() class Post(models.Model): category = models.ForeignKey(Category) Now, I want to get posts of a category: category = Category.objects.get(id=1) posts = category.post_set.all() # this line hit the DB posts = category.post_set.all() # and this line hit the DB again! How to use the cached result in these relations. I use Django rest-framework and it makes DB hit multiple times for each instance. -
Django Broken pipe-Errno 32 Broken pipe error how can I fix it?
I have multiple coins acceptions page I have in models.py def updatedeposit(self, dp): if dp.coin == Coins.BTC: return self.updatedeposit_btc(dp) elif dp.coin == Coins.XMR: return self.updatedeposit_xmr(dp) elif dp.coin == Coins.LC: return self.updatedeposit_ltc(dp) else: raise WalletException('No such deposit option') def updatedeposit_btc(self, dp): if dp.wallet != self: raise WalletException("Can't update a deposit created by another wallet") if dp.status not in STATUS_TO_UPDATE: return dp try: address = self.bitcoind.validate(dp.recv_address) except: raise WalletException("Invalid BTC address") try: unconf_amount = self.bitcoind.unconf_by_addr(address) conf_amount = self.bitcoind.conf_by_addr(address) except: raise WalletException('Bitcoind error') if unconf_amount > conf_amount: dp.status = Status.UNCONFIRMED dp.sats_amount = unconf_amount dp.save() return dp if conf_amount == 0: delta = timedelta(minutes=settings.DEPOSIT_EXPIRATION) if dp.date < timezone.now() - delta: dp.status = Status.EXPIRED dp.save() return dp delta = timedelta(minutes=settings.DEPOSIT_EXPIRATION+40) if dp.date < timezone.now() - delta: dp.status = Status.CANCELLED dp.save() return dp dp.status = Status.WAITING dp.sats_amount = 0 dp.save() return dp and in bitcoin core settings fille bitcoind.py def create_address(self): return self.proxy.getnewaddress(account=self.ACC) def unconf_by_addr(self, addr): return self.proxy.getreceivedbyaddress(addr, minconf=0) i have succeeded to create new btc address from bitcoin-core wallet in the page but when the page refresh to check if there new transaction coming I get this 2 error first Django Version: 3.2.6 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', … -
Page not found error 404 django navbar link
I have an issue with the navbar link where it does find the html page ? my mysite/urls.py """firt_website URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from pages import urls app_name = 'pages' urlpatterns = [ path('', include('pages.urls')), ] my blog/urls.py : from django.contrib import admin from django.urls import path, re_path from . import views app_name = 'main' urlpatterns = [ path('', views.home_page, name='homepage'), path('education/', views.education, name='education'), path('experience/', views.experience, name='experience'), path('portfolio/', views.portfolio, name='portfolio'), ] my navbar.html : <div class="u-custom-menu u-nav-container-collapse"> <div class="u-align-center u-black u-container-style u-inner-container-layout u-opacity u-opacity-95 u-sidenav"> <div class="u-sidenav-overflow"> <div class="u-menu-close"></div> <ul class="u-align-center u-nav u-popupmenu-items u-unstyled u-nav-2"><li class="u-nav-item"><a class="u-button-style u-nav-link" href="Acceuil.html" style="padding: 10px 0px; text-shadow: 0 0 8px rgba(128,128,128,1);">Home</a> </li><li class="u-nav-item"><a class="u-button-style u-nav-link" href="{% url 'main:experience' %}" style="padding: 10px 0px; text-shadow: … -
Customized Login site not showing in Django
I have created a Django App and want to provide a custom Login page with only the possibility to use a Google login. I have implemented the Google login based on this post: https://www.section.io/engineering-education/django-google-oauth/ It actually works fine and when I hit localhost/account/login I am getting a login page: I actually do not want a sign up and a "local" sign in option, I only need a Google login. To achieve this I have created the following folder structure to overwrite the login template (based on https://learndjango.com/tutorials/django-login-and-logout-tutorial): MyApp/templaltes/registration/login.html login.html has the following content: {% extends "base.html" %} {% load i18n %} {% load socialaccount %} {% block content %} <div class="row"> <center><h1>{% trans 'LoginHeading' %}</h1></center> </div> {% if user.is_authenticated %} <p>Welcome, You are logged in as {{ user.username }}</p> {% else %} <a href="{% provider_login_url 'google' %}">Login With Google</a> {% endif %} {% endblock %} I have also added 'DIRS': [str(BASE_DIR.joinpath('templates'))] to the TEMPLATES section in settings.py. Unfortunately I am still seeing the Django default login page. What am I missing? (I have also restarted the dev server to make sure it is not an issue there with the same result) -
Django Bootstrap Modal: CRUD for foreign key model
Models.py: class Dossier(models.Model): name = models.CharField('Name', max_length=200) class Meta: verbose_name = 'Dossier' verbose_name_plural = 'Dossiers' def __str__(self): return self.name class Activity(models.Model): dossier = models.ForeignKey(Dossier, on_delete=models.CASCADE, verbose_name='Dossier') detail = models.CharField('Activity', max_length=1000) topic = models.ForeignKey(Topic, on_delete=models.CASCADE, verbose_name='Topic') source_url = models.CharField('Source URL', max_length=1000, null=True, blank=True) class Meta: verbose_name = 'Activity' verbose_name_plural = 'Activities' def __str__(self): return self.detail Github Repo: username: admin password admin: I'd like to add, edit and delete Activity for a Dossier while editing using Bootstrap-modal asynchronously. I tried to follow this article. urls.py: from django.urls import path from bpsbpoliticaldb import views urlpatterns = [ path('dossiers/edit/<str:pk>/', views.dossier_edit, name="dossier_edit"), path('dossiers/activity/<str:pk>/', views.dossier_activity_create, name="dossier_activity_create"), path('dossiers/activity/add/', views.dossier_activity_add, name="dossier_activity_add"), ] views.py: def dossier_edit(request, pk): dossier = get_object_or_404(Dossier, id=pk) activities = Activity.objects.filter(dossier=dossier) context = {'dossier': dossier, 'activities': activities} return render(request, 'bpsbpoliticaldb/dossier/dossier_edit.html', context) def dossier_activity_create(request, pk): data = dict() if request.method == 'POST': form = ActivityForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = ActivityForm() context = {'form': form} data['html_form'] = render_to_string('bpsbpoliticaldb/activity/partial_activity_create.html', context, request=request, ) return JsonResponse(data) forms.py: from django.forms import ModelForm from django import forms class ActivityForm(ModelForm): class Meta: model = Activity widgets = { 'detail': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}), 'topic': forms.Select(attrs={'class': 'form-control'}), 'source_url': forms.TextInput(attrs={'class': 'form-control'}), } fields = ['detail', 'topic', 'source_url'] … -
Django 2 schedulers being run
These are my files- from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api' def ready(self): import api.scheduler as scheduler scheduler.start() from apscheduler.schedulers.background import BackgroundScheduler def fetch_new_raw_data(): '''Fetches new data''' def start(): scheduler = BackgroundScheduler() scheduler.add_job(fetch_new_raw_data, 'interval', minutes=1) scheduler.start() fetch_new_raw_data() When using py manage.py runserver django spawns 2 processes, each one will start a scheduler. Is there a way to load up the scheduler only in 1 process and use the same in both or is it ok for them to start their own scheduler? -
ID which consists of slug and uuid Django Rest Framework
I want to identify my database items over id which consists of slug and uuid, so if two users add f.e. name of the item: "Mercedes A40", they will be stored in database with different ids f.e. "mercedes-a40-25b6e133" and "mercedes-a40-11ac4431". What should I type inside my Product model in id field? How can I combine it? id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(max_length=250, unique_for_date='published') -
How to produce and consume JSON messages between Django services using Redis as a message queue?
I am trying to find a way to enable communication between two Django services using Redis as a message queue. One service would produces JSON data, publish it to the queue and the other one would consume the message. Something similar to what I want to achieve is described here using Spring Boot and RabbitMQ: https://www.javainuse.com/spring/spring-boot-rabbitmq-consume Any articles or suggestions would mean a lot. -
Using a for loop with Mapbox
I want to do what is done in this example: https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/ but instead of adding each point manually i want to insert the data from my forms in a for loop. I have been succesful with using for loops to add markers in this format: {% for markers in marker %} {% if markers.PlantName in Bær %} var marker = new mapboxgl.Marker({ color: 'red'}) {% elif markers.PlantName in Frugt %} var marker = new mapboxgl.Marker({ color: 'orange'}) {% else %} var marker = new mapboxgl.Marker({ color: 'green'}) {% endif %} .setLngLat([{{ markers.lon }}, {{ markers.lat }}]) .setPopup(new mapboxgl.Popup().setHTML("<p>{{markers.PlantName}}<p>")) .addTo(map); {% endfor %} But in the example they add the points differently. Thanks in advance! -
django-import-export: Import many to many field
I have a model "Website", which can have multiple categories: Model.py class Website(models.Model): ... uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) category = models.ManyToManyField('Category', related_name='website_category') country = models.ForeignKey('Country', null=True, blank=False, on_delete=models.SET_NULL, related_name='website_country') language = models.ForeignKey('Language', null=True, blank=False, on_delete=models.SET_NULL, related_name='website_language') ... I'm willing to import multiple, comma separated, categories for each website via xlsx file. Following is my admin file: Admin.py class WebsiteResource(resources.ModelResource): category = fields.Field( column_name='category', attribute='category', widget=ManyToManyWidget(Category, ',', 'name')) country = fields.Field( column_name='country', attribute='country', widget=ForeignKeyWidget(Country, 'name')) language = fields.Field( column_name='language', attribute='language', widget=ForeignKeyWidget(Language, 'name')) def before_import_row(self, row, row_number=None, **kwargs): try: row['uuid'] = uuid.uuid4() row['cost_price'] = row['publication_price'] * (row['percentage']/100) row['url'] = clear_url(row['url']) row['outreached_by'] = get_outreached_by_details(kwargs['user']) except Exception as e: raise ValidationError(e) class Meta: model = Website import_id_fields = ['uuid'] fields = (....) class WebsiteAdmin(ImportMixin, admin.ModelAdmin): resource_class = WebsiteResource .... def get_import_formats(self): formats = ( # base_formats.CSV, base_formats.XLSX, ) return [f for f in formats if f().can_export()] class meta: model = Website Everything else if working smoothly but since this category field is a many to many field so I have an exception when I confirm import. Exception: insert or update on table "GPFY_website_category" violates foreign key constraint "GPFY_website_category_website_id_32320ddd_fk_GPFY_website_uuid" DETAIL: Key (website_id)=(3ed6ae85-d309-4e7f-b2d9-5a74ddeb3b90) is not present in table "GPFY_website". Maybe this is because when an … -
Django password_change_done not found
I have a small application that I'm writing, but I have came into some trouble with the password changing elements used with the Django authentication framework. But I always get the error after changing a password that: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Here is my code below: #account urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ #Password Changes URLs path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] This is my directory structure for the login system: Directory Structure Here's the password_change.html file: <h3 style="text-align: center;">Change your password</h3> <div class="login-form" style="text-align: center; "> <form method="post"> {{ form.as_p }} <p><input type="submit" value="Change"></p> {% csrf_token %} </form> </div> Any help would be greatly appreciated!