Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I insert a digital signature obtained by the Openssl library into a pdf file with python
publickey = crypto.dump_publickey(crypto.FILETYPE_PEM,pkey) print(publickey) sign = crypto.sign(pkey, open(fs.path(Doc.name), 'rb').read(), "SHA512") print(sign) -
Filtering using <a> tag (django, python)
I have got some pictures with tags on my page and I would like them to be used as filtering by the category. So after clicking on one of the pictures it would filter the results by the category. So that would be the filter, that I would like to connect to one of the pictures: item_list = item_list.filter(category__pk=1) html <div class="col-md-4 overlay zoom"> <a href="/"> <div style="position:relative;"> <img src="{% static '/img/category_choice/bike1.png' %}" class="img-fluid"> <div class="card-img-overlay"> <h2 class="card-title" style="text-align: center; color: aliceblue; position: absolute; bottom:5px;"> Gravel Bikes </h2> </div> </div> </a> </div> -
SignatureDoesNotMatch - Boto3 Django-storages
I have the following config: Django/DRF Boto3 Django-storages I am using an IAM user credentials with one set of keys. I have removed all other sets of keys including root keys from my account, to eliminate keys mismatch. I created a new bucket my-prod-bucket. Updated the bucket name settings in my env file. I ran python3 manage.py collectstatic and it created the new bucket without a problem. my .env: AWS_ACCESS_KEY_ID=something AWS_SECRET_ACCESS_KEY=something AWS_STORAGE_BUCKET_NAME=my-prod-bucket my settings.py (using python-decouple to grab from .env): AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.ca-central-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_REGION_NAME = 'ca-central-1' AWS_HEADERS = { 'CacheControl': 'max-age=86400', } AWS_STATIC_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) STATICFILES_STORAGE = 'portal.storage_backends.StaticStorage' # ======= AWS_DEFAULT_ACL = None AWS_AUTO_CREATE_BUCKET = True S3_USE_SIGV4 = True I can upload and delete however when I try to download a file I get: <Error> <Code>SignatureDoesNotMatch</Code> <Message> The request signature we calculated does not match the signature you provided. Check your key and signing method. </Message> <AWSAccessKeyId>AKIA6FUWELHP36HW6QOT</AWSAccessKeyId> <StringToSign> AWS4-HMAC-SHA256 20200211T215631Z 20200211/ca-central-1/s3/aws4_request 703b799a80d9efd9f9e06a01ab30a8a721f2a9bafe6a3d5c92b045ea769b0d87 </StringToSign> <SignatureProvided> 46bd882624f966d9cb8914d279f7c8f91a2b3e5e577525c13069e29f8891c1ee </SignatureProvided> <StringToSignBytes> 41 57 53 34 2d 48 4d 41 43 2d 53 48 41 32 35 36 0a 32 30 32 30 30 32 31 31 54 … -
Can I validate Django form entries in real time?
I have created an HTML form from a Django form model. Is there a way I can validate user entries in each form field in real time? For example, I have a field where users must enter their phone number according to a regex (e.g. +1XXX-XXX-XXXX). Can I show an error message if they do not enter according to the regex? -
Issue with django DB connectivity on heroku
I am new to django and might be missing something obvious. I intend to create a simple project and deploy on heroku. Since sqlite3 is not supported on heroku, I have setup a postgres instance on elephantsql. I have changed the settings.py file and able to connect to the postgres instance from http://127.0.0.1:8000/. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "dummy", "USER": "dummy", "PASSWORD": "dummy", "HOST": "dummy", "PORT": "5432" } } However, I am still not able to connect from heroku. ProgrammingError at / relation "home_signup" does not exist LINE 1: ...e_signup"."email", "home_signup"."timestamp" FROM "home_sign... ^ I have gone through the postgres db which heroku offers, but the free version is limited to 10rows only.So, thought of using elephantsql which has better free offering. Any pointer will be great help. -
TypeError: 'DeferredAttribute' object is not subscriptable in models.py
I have this code in my models.py I just want that once the admin has finished filling the StudentsEnrollmentRecord it will get all related data in ScheduleOfPayment and post it in StudentsPaymentSchedule thats why i have this filter scheduleofpayment = ScheduleOfPayment.objects.filter(Payment_Type=instance.Payment_Type, Education_Levels=instance.Education_Levels, Courses=instance.Courses) / class StudentsPaymentSchedule(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Schedule = models.CharField(max_length=500, null=True, blank=True) Amount = models.FloatField(null=True, blank=True) Student_Payment_Date = models.DateField(null=True, blank=True) Paid_Amount = models.FloatField(default=0, null=True, blank=True) Balance = models.FloatField(null=True, blank=True) Remarks = models.TextField(max_length=500, null=True, blank=True) @receiver(pre_save, sender=StudentsEnrollmentRecord) def get_older_instance(sender, instance, *args, **kwargs): try: instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk) except StudentsEnrollmentRecord.DoesNotExist: instance._old_instance = None print("dddd") @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): if not created: older_instance = instance._old_instance if older_instance.Payment_Type != instance.Payment_Type or \ older_instance.Education_Levels != instance.Education_Levels: StudentsPaymentSchedule.objects.filter( Students_Enrollment_Records=instance ).delete() else: return None scheduleofpayment = ScheduleOfPayment.objects.filter(Payment_Type=instance.Payment_Type, Education_Levels=instance.Education_Levels, Courses=instance.Courses) amounts = ScheduleOfPayment.Amount date=ScheduleOfPayment.Date sched = ScheduleOfPayment.Remark for i , each in enumerate(scheduleofpayment): amount = amounts[i] date = date[i] remarks = sched[i] StudentsPaymentSchedule.objects.create( Students_Enrollment_Records=instance, Payment_Schedule = date, Amount = amount, Remarks = remarks ) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) strands = models.ForeignKey(strand, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) … -
Django -Make writable multiple serializers using def create?
i am trying to create a nested serializer using DJANGO REST FRAMEWORK. But I don't know how to use create update methods in serializer.py. I already have created models and some working serializers.and i want that all this serializer will be writable and editable but i don't know how to do this i tried but i could not get actual result.here is my code. from rest_framework import serializers from ..models import about, education, work, project, skill, language, hobbies, techonogies from django.contrib.auth.models import User # from drf_writable_nested.serializers import WritableNestedModelSerializer class EducationSerializer(serializers.ModelSerializer): class Meta: model = education exclude = ['about','created_by'] class WorkSerializer(serializers.ModelSerializer): class Meta: model = work exclude = ['about','created_by'] class ProjectSerializer(serializers.ModelSerializer): class Meta: model = project exclude = ['about','created_by'] class LanguageSerializer(serializers.ModelSerializer): class Meta: model = language exclude = ['about','created_by'] class SkillSerializer(serializers.ModelSerializer): class Meta: model = skill exclude = ['about','created_by'] class HobbiesSerializer(serializers.ModelSerializer): class Meta: model = hobbies exclude = ['about','created_by'] class TechSerializer(serializers.ModelSerializer): class Meta: model = techonogies exclude = ['about','created_by'] class PersonalSerializers(serializers.ModelSerializer): class Meta: model = about exclude = ['user'] def create(self, validated_data): validated_data['user'] = self.context['request'].user return super().create(validated_data) class AaProfileSerializer(PersonalSerializers): educations = EducationSerializer(many=True, required=False) works = WorkSerializer(many=True, required=False) projects = ProjectSerializer(many=True, required=False) languages = LanguageSerializer(many=True, required=False) skills = SkillSerializer(many=True, required=False) hobbie = … -
Merge two objects in django
I am building ecommerce app I use sessions to store carts then if user log in then assign the session cart to user the issue is when user has an existing cart assigned to his account and a new session cart , So how to merge these to carts for the same user , or force the app to keep only one Cart per user views : def add_to_cart(request): cart_session = request.session.get('cart') item = Item.objects.get(pk=request.POST['item_id']) if request.user.is_authenticated: //some code // else: if cart_session: cart = Cart.objects.get(pk=cart_session) cart_item = Order_item.objects.all().filter( item=item, shopping_cart=cart_session).first() if cart_item: cart_item.qty += 1 cart_item.save() messages.success(request, 'cart updated') else: cart_item = Order_item(shopping_cart=cart, item=item) cart_item.save() cart.item.add(cart_item) cart.save() messages.success(request, 'Added to cart') print(cart.id) else: cart = Cart() cart.save() cart_item = Order_item(shopping_cart=cart, item=item) cart_item.save() cart.item.add(cart_item) messages.success(request, 'Added to cart') request.session['cart'] = cart.id return HttpResponseRedirect(request.META.get('HTTP_REFERER')) and here how i assign session cart to user: cart_session = request.session.get('cart') if request.user.is_authenticated: if cart_session: cart = Cart.objects.get(pk=cart_session) user = User.objects.get(pk= request.user.id) cart.user = user cart.save() models class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) item = models.ManyToManyField('Order_item') is_ordered = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=True) class Order_item(models.Model): shopping_cart = models.ForeignKey(Cart, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) qty = models.IntegerField(default=1) time = models.DateTimeField(auto_now_add=True) -
I am creating a folder with a .txt file
in windows it works but when I test it on a ubuntu server the answer is [Errno 13] Permission denied: 'txts' the code is: def generarTxt(request,id): now = datetime.now() fac= Factura.objects.get(pk=id) #Obtenemos los datos a guardar en el txt datos = request.GET['datos'] #Creamos la ruta donde se van almacenar las carpetas os.makedirs('txts/'+str(request.session['usuario'][2])+'/out', exist_ok=True) # Creamos el nombre del archivo nombre = "datosFacturaNo_"+str(fac.numFactura)+'.txt' #establecemos la ruta ruta = 'txts/'+str(request.session['usuario'][2])+'/out/' #Creamos y abrimos el archivo f = open(ruta + nombre, 'w') #Sobreescribimos el archivo f.write(datos.replace('_', '\n')) f.close() -
django-celery netcat spam within docker container
I am trying to run celery in a separate docker container alongside a django/redis docker setup. When I run docker-compose up -d --build, my logs via docker-compose logs --tail=0 --follow show the celery_1 container spamming the console repeatedly with Usage: nc [OPTIONS] HOST PORT - connect nc [OPTIONS] -l -p PORT [HOST] [PORT] - listen -e PROG Run PROG after connect (must be last) -l Listen mode, for inbound connects -lk With -e, provides persistent server -p PORT Local port -s ADDR Local address -w SEC Timeout for connects and final net reads -i SEC Delay interval for lines sent -n Don't do DNS resolution -u UDP mode -v Verbose -o FILE Hex dump traffic -z Zero-I/O mode (scanning) I am able to get celery working correctly by removing the celery service from docker-compose.yaml and manually running docker exec -it backend_1 celery -A proj -l info after docker-compose up -d --build. How do I replicate the functionality of this manual process within docker-compose.yaml? My docker-compose.yaml looks like version: '3.7' services: backend: build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db - redis links: - db:db celery: build: ./backend command: celery … -
How to fetch and display data from Django Model without invoking the URL
I have a Class-Based ListView as shown below: class JobByStateView(ListView): model = State template_name = 'jobs/jobs_by_state.html' context_object_name = 'state_list' ordering = ['name'] paginate_by = 15 I have added the path to urls.py file as shown below: path('jobs/', JobByStateView.as_view(), name='job-by-state'), And this how my template looks: <div class="row"> <div class="col-md-4"> <ul class="list-unstyled mb-0"> {% for state in state_list %} {% if forloop.counter|divisibleby:"5" == False %} <li> <a href="#">{{state.name}}</a> </li> {% else %} <li> <a href="#">{{state.name}}</a> </li> </ul> </div> <div class="col-md-4"> <ul class="list-unstyled mb-0"> {% endif %} {% endfor %} </ul> </div> </div> When I try to access this templates via the url (http://localhost:8000/jobs) it works as expected and displays the data on the screen. But when I try embed this template within another template as shown below, nothing gets displayed on the web page. {% include 'jobs/jobs_by_state.html' %} I would like to display this template as a widget within another template. Really appreciate, if anyone could please help me in fixing this issue. Thank you so much in advance for your time and help! -
Django mysql query only returns first column
I have a small test app i am working on and at the moment no matter what i do query wise the object only ever returns the first field from the model not the matching row data? if it print the query i get the correct mysql results so unsure what i am doing wrong here? Model: class NotesPost(models.Model): noteUrl = models.CharField(default='', max_length=16, blank=True, null=True) notePostDate = models.CharField(default='', max_length=40) noteName = models.CharField(max_length=255) noteMessage = models.TextField() def __str__(self): return self.noteUrl Now i do the following in shell from testnotes.models import NotesPost test = NotesPost.objects.filter(noteUrl='onjgRZBYTG') However what i receive is: >>> test <NotesPost: onjgRZBYTG> >>> print(test.query) The result i get back (sorted for this post) SELECT `notespost`.`id`, `notespost`.`noteUrl`, `notespost`.`notePostDate`, `notespost`.`noteName`, `notespost`.`noteMessage` FROM `notespost` WHERE `notespost`.`publicUrl` = 'onjgRZBYTG' Which in the db is correct and returns the entire row as expected? So at the moment i am unsure why i am only receiving the first column of the query object and not the whole row, as i would like to update the row and present data from the row. Many thanks -
How to convert FBV to ListView in Django
I want to convert the FBV function to ListView. But I don't know how to handle the value of slug. How to get the value of slug in ListView? view.py def category(request, slug=None): current_ct = None categories = Category.objects.all() products = Product.objects.filter(ready=True) if slug: current_ct = get_object_or_404(Category, slug=slug) products = products.filter(category=current_ct) return render(request, 'home.html', {'current_ct': current_ct, 'categories': categories, 'products': products}) url.py path('category/<slug>/', category, name="test"), get_absolute_url() in model.py def get_absolute_url(self): return reverse("test", kwargs={"slug": self.slug}) -
django.db.utils.OperationalError: FATAL: database does not exist (postgres / deploy to digitalocean)
I am trying to deploy a project with digital ocean. I followed the instructions found at https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 Some of the important ones: I ran: postgres=# CREATE DATABASE jobzumoDB; CREATE DATABASE then: postgres=# CREATE USER admin WITH PASSWORD '123'; CREATE ROLE postgres=# ALTER ROLE admin SET client_encoding TO 'utf8'; ALTER ROLE postgres=# ALTER ROLE admin SET default_transaction_isolation TO 'read committed'; ALTER ROLE postgres=# ALTER ROLE admin SET timezone TO 'UTC'; ALTER ROLE postgres=# GRANT ALL PRIVILEGES ON DATABASE jobzumoDB TO admin; GRANT set the following in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'jobzumoDB', 'USER':'admin', 'PASSWORD':'123', 'HOST':'localhost', 'PORT':'', } then tried to run: ~/jobzumo/manage.py makemigrations and got: File "/home/justin/jobzumo/env/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: database "jobzumoDB" does not exist Two things: I have the ALLOWED_HOSTS settings set to a domain I haven't connected to digital ocean yet, don't know if this could be causing a problem ( but that is what instructions said to do). Also, I ran: pip install django gunicorn psycopg2 (from digitial ocean) but a tutorial on youtube said it was very important to now install psycopg2-binary instead, however, I did not do this as the video was veering far … -
How can I make DRF Serializer create() function only create an such an entry does not exist yet?
I have two tables, which are connected with each other through a cross table. (Recipes <--> Ingredients) My Serializer works ok, I can send POST-Requests and it saves everything. The problem ist, that every time a new Recipe comes in with let just say the Ingredient "Milk" then my Serializer creates a new entry in my database named Milk, although I have an already existing entry "Milk" in my database. How do I tell my Serializer to use the Id of an already existing entry instead of creating a new one every time for the cross table. Here is how I thought I could fix it, but it clearly doesn't: class RecipeIngredientSerializer(serializers.ModelSerializer): ingredient = IngerdientSerializer() class Meta: model = recipe_ingredients fields = ['amount', 'unit', 'ingredient'] def create(self, validated_data): ingredient_validated_data = validated_data.pop('ingredient') ingredient_serializer = self.fields['ingredient'] ingredientDict = dict(ingredient_validated_data) // This is where I try to check if there is already an ingredient with the name from the form ingredientObj = ingredient.objects.all().filter(ingredient_name=ingredientDict['ingredient_name']). if not ingredientObj: ingredient_instance = ingredient.objects.create(**ingredientDict) validated_data['ingredient'] = ingredient_instance else: ingredient_instance = ingredient_serializer.create(ingredientDict) validated_data['ingredient'] = ingredient_instance recipe_ingredients_instance = recipe_ingredients.objects.create(**validated_data) return recipe_ingredients_instance This code also seems to work, at least I find an existing ingredient, but after the last create() it … -
Untangle Django ManyToMany relationship in graph structure
I would like to build a graph using Django models; the nodes are "Goals" and have connections to "higher" and "lesser" goals. The documentation is quite explanatory and I found some examples here and there, but none including self-many-to-many connections and there it is where things get confusing! This is my model: class Goal(models.Model): """Goals are the objectives to be achieved and represents the nodes of the tree.""" title = models.CharField(max_length=200, blank = False, null = False) completed = models.BooleanField(default=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) connections = models.ManyToManyField("self", blank=True, symmetrical=False, related_name="ins", through='Edge') def __str__(self): return f'{self.title} - {self.description}' class Edge(models.Model): """Object connecting two goals in a logic way.""" to_goal = models.ForeignKey(Goal, related_name='lesser_goals', on_delete=models.CASCADE) from_goal = models.ForeignKey(Goal, related_name='higher_goals', on_delete=models.CASCADE) I have two small questions: At the moment the model works, but it is very confusing to add connections (I always end up adding the other way around and the names, no matter how I put them, don't help me). Do you have a foolproof way to get organized in these situations? Like some naming conventions, or rules of thumbs or even magic spells. The on_delete=models.CASCADE is obviously wrong, but I didn't figure out yet what I need to put there. When I … -
How to don't run unaplly migrations
when I use command: python3 manage.py migrate my_app 0001_initial all next migrations will be unapply. How to don't do this, I want the all follow migrations stay. -
Django Redirect Urls
I have some problem about finding how to redirect an url. So when a user is logged in my site and click the logout button he is now logged out, which is fine, but I want to redirect him to the login page, and I dont know how to do it. Thanks you from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('', include('sms.urls')), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] -
How to access the image in django template?
image is not showing in the template how to access all, all the code below model.py image = models.ImageField(upload_to='todoimages/%Y/%m/%d', max_length=255, blank=True, null=True ) home.html <img class="img-fluid rounded mb-5" src="{{todoItem.image}}" alt="{{todoItem.title}}"> settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/') -
How to render data on modal
def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You're now logged in as {username}") return redirect("main:homepage") else: messages.error(request, "Invalid Username or Password!!") else: messages.error(request, "Invalid Username or Password!!") form = AuthenticationForm return render(request, "main/login.html", {"form": form}) I want to render the form which is a ModelForm to a modal but as modal doesn't have any url how can I tell my view function to where to render ?? url for login_request is path('login/', login_request) help -
Trying to emit socketio message in Django Rest Framwork view sometimes fails
There are certain cases, where my Django Rest Framework application needs to send a notification using socketio to another server. Function for emitting the notification is included in the views.py file, and it's called directly from the Rest request handlers when needed. Most of the time it works fine, however sometimes call to emit() throws an exception. So far at least three different exceptions have occurred. The application is run on Elastic Beanstalk. Code for emitting the message: def send_request(message): sio = socketio.Client() @sio.event def connect(): sio.emit(settings.KEY, message) # Exception happens on this line, if it happens at all sio.wait() sio.disconnect() sio.connect(settings.URL,transports='websocket') Logs from three different errors below: [Sun Feb 09 15:36:44.732110 2020] [:error] [pid 1713] Exception in thread Thread-262167: [Sun Feb 09 15:36:44.732131 2020] [:error] [pid 1713] Traceback (most recent call last): [Sun Feb 09 15:36:44.732133 2020] [:error] [pid 1713] File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner [Sun Feb 09 15:36:44.732136 2020] [:error] [pid 1713] self.run() [Sun Feb 09 15:36:44.732138 2020] [:error] [pid 1713] File "/usr/lib64/python3.6/threading.py", line 864, in run [Sun Feb 09 15:36:44.732141 2020] [:error] [pid 1713] self._target(*self._args, **self._kwargs) [Sun Feb 09 15:36:44.732143 2020] [:error] [pid 1713] File "/opt/python/run/venv/local/lib/python3.6/site-packages/engineio/client.py", line 665, in _write_loop [Sun Feb 09 15:36:44.732145 2020] [:error] … -
Can Excel be integrated as an interactive part of a website? (Django)
As I'm completely new to this community, I'm unaware of where to ask this type of question. I have very little experience with coding (only taken Django, Python and Javascript courses on Udemy) and am now trying to make a teaching website where students have to solve problems on the website. To make the website more 'special' I hope to be able to make Excel available and interactive (or something similar) on the website - example: mockup of website Is this an 'easy' app (relatively speaking to a new programmer) to make? And is it possible in a framework like Django? If any of you have any references to what I can read to become better - please feel free to share. I'm sorry if this is not the right place to ask these types of 'home project' questions! -
Django data channeling from views
I want to channel my data in the view. The problem with the method below, which works fine, is that i cannot use try except. How can I iterate over dev object to build the data in the context dictionary? So that i can use try catch? def DeviceDetailView(request, device_name): dev = DeviceDetail.objects.values() context = { 'data': [(a, appl.objects.filter(device_name=device_name).values_list(a['value'], flat=True)[:1]) for a in dev], } return render(request, 'applications/device.detail.html', context) -
Get detail by Unique ID but not PK in Django Rest Framework
I am trying creating Rest API using DRF. Wanted to get detail by using UniqueId. I can get it using I wanna use unique id created in the model field. Models.py from django.db import models from rest_api.util import unique_slug_generator from django.urls import reverse # Create your models here. class Jobs(models.Model): token_id = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=100) url = models.URLField() environment = models.CharField(max_length=100, null=True) runtestnow = models.BooleanField(default=False) def __str__(self): return self.name def get_absolute_url(self): return reverse('token_id', kwargs={'token_id':self.token_id}) class Queue(models.Model): tokenid = models.ForeignKey(Jobs, on_delete=models.CASCADE) date = models.DateField(auto_now=True) def __str__(self): return self.tokenid class VM(models.Model): vm_count = models.IntegerField(default=120) def __str__(self): return f"VM Count: {self.vm_count}" Urls.py from django.urls import path, include from . import views from .views import (RegisterTestMethodView, RegisterTestMethodViewDetail, CheckStatusView, ReleaseTokenView ) from rest_framework import routers from rest_framework.authtoken.views import obtain_auth_token from rest_framework.urlpatterns import format_suffix_patterns from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView router = routers.DefaultRouter() router.register('jobs', views.JobsView) urlpatterns = [ path('', include(router.urls)), path('registertestmethod/', RegisterTestMethodView.as_view()), path('registertestmethod/<int:pk>/', RegisterTestMethodViewDetail.as_view()), path('checkstatus/<int:pk>', CheckStatusView.as_view()), path('checkstatus/<slug:token_id>', CheckStatusView.as_view()), path('releasetoken/<int:pk>', ReleaseTokenView.as_view()), ] Serializers.py from rest_framework import serializers from .models import Jobs from django.utils.crypto import get_random_string class JobsSerializers(serializers.HyperlinkedModelSerializer): token_id = serializers.CharField(default=get_random_string(length=25)) class Meta: model = Jobs fields = ('id', 'name', 'url','runtestnow','token_id') class CheckStatusSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Jobs fields = ('id','runtestnow') class RegisterTestMethodSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = … -
Is it possible to define the success_url in django without kwargs
I am elaborating on the tutorial in the django docs to build a voting app. What I try to achieve is to be able to delete a candidate and, at success, get back to the detailview of the election. I know I could just add another parameter to the url like (full template below) <a href="{% url 'candidate_delete' c.id object.id %}" class="btn btn-danger fa fa-trash" class></a> I would like to know whether it is possible to use a post method (although there is no form). I did some research, found the 'next' parameter, but it does not get through. It looks like it needs a form, since all examples are using the 'next' within a form. I also tried setting the success_url based on the election the to-be-deleted-candidate is ForeignKey-d to, but that generates the error: ImproperlyConfigured at /elections/candidate/delete/13/ The included URLconf '1' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. This is the view: class CandidateDelete(LoginRequiredMixin, DeleteView): model = Candidate template_name = 'election/delete.html' def get_object(self): obj = super().get_object() print(self.request.POST) election = Election.objects.get(id=obj.poll_id) if not election.owner_id == self.request.user.id: raise Http404 return …