Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - DeleteView with pk. No Posty matches the given query
Heeey I have a problem with get_success_url. Namely I would delete a comment from post and then should go back to the page with the post. On this moment have i "No Posty matches the given query." I dont have idea how i can resolve this. I know how to reverse on page with no pk ;( Models class Posty(models.Model): title = models.CharField(max_length=250, blank=False, null=False, unique=True) sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True) content = models.TextField(max_length=250, blank=False, null=False) image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])]) author = models.ForeignKey(Profil, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(auto_now_add=True) T_or_F = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Posty' def __str__(self): return str(self.title) def save(self, *args, **kwargs): if not self.sub_title: self.sub_title = slugify(self.title) super(Posty,self).save(*args, **kwargs) def get_absolute_url(self): return reverse('home:detail_post', kwargs={"id":self.id}) Views class delete_post_comment(DeleteView): model = CommentModelForm() template_name = 'delete_comment_from_post.html' def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Posty,id=id_) def get_success_url(self): return reverse('home:detail_post') Urls urlpatterns = [ path('', home, name='home'), path('forum/', create_post_and_comment, name='forum'), path('delete_post/<int:pk>/', delete_post_view.as_view(model=Posty), name='delete_post'), path('update_post/<int:pk>/', update_post_view.as_view(model=Posty), name='update_post'), path('delete_post_comment/<int:pk>/', delete_post_comment.as_view(model=CommentPost), name='delete_post_comment'), path('update_post_comment/<int:pk>/', update_post_comment.as_view(model=CommentPost), name='update_post_comment'), path('detail_post/<int:pk>/', contact, name='detail_post'), path('testuje/<int:pk>/', contact, name='test') Forms class CommentModelForm(forms.ModelForm): content1 = forms.CharField(widget=forms.Textarea(attrs={})) class Meta: model = CommentPost fields = ('content1',) -
NGINX-WSS connection failing but WS connection works
I am having trouble implementing wss connections in my app over port 443. When connecting to my app over port 80 I able to connect to the socket(ws connection). my app works fine with HTTPS requests(can log in and request data) but cannot handle wss properly. The console logs failed to connect, with no server error codes. nginx file server 80: server { listen 80; server_name test.com; root html\test.com; index index.html index.htm; location /api/ { proxy_pass http://xxx.xxx.xxx.xx:xxxx; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /widget/{ proxy_pass http://xxx.xxx.xxx.xx:xxxx/widget/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } The above code works fine nginx file server 443: server { listen 443 ssl; server_name test.com; root html\test.com; index index.html index.htm; ssl_certificate C:/Certbot/live/test.com/fullchain.pem; ssl_certificate_key C:/Certbot/live/test.com/privkey.pem; location /api/ { proxy_pass http://xxx.xxx.xxx.xx:xxxx; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /widget/{ proxy_pass http://xxx.xxx.xxx.xx:xxxx/widget/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } I am able to make https requests but I … -
How can I create group with the same name as the role name in DRF generics APIView
I'm trying to create a new group each time a user create a role, the problem I keep having errors in my code logic, and I don't really know what to do to make it work, here is what I came with so far : from rest_framework import generics from django.contrib.auth.models import Group class CreateRoleView(generics.ListCreateAPIView): queryset = Roles.objects.all() serializer_class = CreateRolesSerializers permission_classes = (IsAuthenticated,) def post(self, request, *args, **kwargs): role_name=self.kwargs['role_name'] created = Group.objects.create(name=role_name) return self.create(request, created, *args, **kwargs) and here is a screen of my problem : enter image description here -
Django Rest Framework save multiple serializers in a celery task
Am using Django rest framework, Celery, and RabbitMQ for my aplication. I have a task that does some data processing and saves the results as objects in my Django application. The task has two different results that need to be saved, so two model serializers are needed. The problem is that when the task is performed only one of the models is being saved. I tried the method while it was not a celery task and it worked perfectly, and i don't know what changes when it is run as a task that it won't work any more. this is the code runned in the task: def createMBGSimulations(petition_id): ... Data process ... prices = s_Q.tolist() lists_ci = cis.tolist() serializer = serializers.PriceSerializer(data={}) serializer_ci = serializers.ConfidenceIntervalSerializer(data={}) if serializer.is_valid(): petition = models.Petition.objects.get(pk=petition_id) serializer.save(prices=prices, petition=petition) if serializer_ci.is_valid(): serializer_ci.save(ci=lists_ci, petition=petition) petition.clean() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django REST Framework: handle exception for custom permission class
I built a custom permission class in Django that verifies the remote IP address of the request. If the request IP is one that's allowed, the has_permission class returns True, otherwise it returns False and the view responds with status code 403.. class isVerifiedServer(permissions.BasePermission): def has_permission(self, request, view): ip_addr = request.META['REMOTE_ADDR'] return ip_addr == some_verified_ip But I want the view to return 404 when this test fails, which is what the server responds with by default when a request is sent to a non-existent URL endpoint. I want to do this to make sure no one can figure out what a valid endpoint is. DRF documentation says the following about changing the exception response of a custom permission class: Custom permissions will raise a PermissionDenied exception if the test fails. To change the error message associated with the exception, implement a message attribute directly on your custom permission. Otherwise the default_detail attribute from PermissionDenied will be used. Similarly, to change the code identifier associated with the exception, implement a code attribute directly on your custom permission - otherwise the default_code attribute from PermissionDenied will be used. I've tried setting many attributes to achieve this, but the response is still always … -
Cannot get autocompletion on Django Model Manager in PyCharm
I'm trying to use autocompletion to get methods like filter, count, create, etc. in PyCharm, but I can't seem to grab them from the objects attribute. It seems like this specific attribute is not working - since PyCharm provides autocompletion for the class itself, for example, just not objects. I've tried refreshing the virtual environment as well, but it seems like it might just not be a supported features. It doesn't autocomplete in either Pycharm 2020.3 or Pycharm 2021.2., or in abstract or concrete classes. -
DRF serialize foreign key return object, not ID
I have a OneToMany relation. One Construction and many Cameras. I want to return all Building object fields in CameraSerializer Problem When I perform POST request (create new Camera object) { "name": "CameraName", "url": "CameraUrl", "building": 2 } I have an error { "building": { "nonFieldErrors": [ "Invalid data. Expected a dictionary, but got int." ] } } Reason of error -- Django expects FULL Construction object, but I want to set only ID How can I fix the error? models.py class Construction(models.Model): """ Объект строительства""" developer = models.ForeignKey( Developer, related_name="constructions", on_delete=models.CASCADE ) name = models.CharField(max_length=100) plan_image = models.ImageField(upload_to=name_image, blank=True, null=True) ... def __str__(self): return self.name class Camera(models.Model): building = models.ForeignKey( Construction, related_name="cameras", on_delete=models.CASCADE ) name = models.CharField(max_length=100) url = models.CharField(max_length=100) ... def __str__(self): return self.name serializers.py class ConstructionSerializer(serializers.ModelSerializer): coordinates = MyPointField() deadline = serializers.DateTimeField(format=TIME_FORMAT) cameras_number = serializers.SerializerMethodField() developer_name = serializers.SerializerMethodField() events = serializers.SerializerMethodField() class Meta: model = Construction fields = ( 'id', 'developer', 'developer_name', 'name', 'plan_image', 'address', 'coordinates', 'deadline', 'workers_number', 'machines_number', 'cameras_number', 'events' ) read_only_fields = ('workers_number', 'machines_number', 'cameras_number', 'events') def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance class CameraSerializer(serializers.ModelSerializer): frames = FrameSerializer(many=True, read_only=True) building = ConstructionSerializer() class Meta: model = Camera fields = ( 'id', 'building', 'name', 'url', … -
Error: Deploying Django app into Heroku push rejected
Hello Can anyone help me with this error. I am trying to run git push heroku :main but this is continuously failing. I am trying to deploy heroku django app. Enumerating objects: 536, done. Counting objects: 100% (536/536), done. Delta compression using up to 2 threads Compressing objects: 100% (472/472), done. Writing objects: 100% (536/536), 102.08 KiB | 967.00 KiB/s, done. Total 536 (delta 291), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-18 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Python has released a security update! Please consider upgrading to python-3.8.11 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.8.10 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting appdirs==1.4.4 remote: Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) remote: ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /tmp/build_a3e7552b/requirements.txt (line 2)) (from versions: none) remote: ERROR: No matching distribution found for apturl==0.5.2 (from -r /tmp/build_a3e7552b/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push … -
Pulling profile data from Google OAuth2 for custom Django User Model
I am currently attempting to program a web app using the Django and React Framework, and want to add a feature in which users can sign up with their Google Accounts. Once a certain user is signed in with their Google Account, I would like to extend the profile using a Django User (or AbstractBaseUser) Model with more fields such as some pictures or favorite colors. However, I am lost on how and where to implement this in my code. Any help would be greatly appreciated! -
Django manage.py - differentiate runserver and/or actual server running from other command contexts?
Suppose I have some code in one of the urls.py that really shouldn't be run during a lot of the Django management/maintenance commands. Is there a way to know what context the code is being loaded for, other than checking sys.argv directly and explicitly? ... def setup_at_startup(): """code here would definitely fail on python manage.py makemigrations/migrate but let's it's discovery code to figure out some services """ #pseudo-code if django.command in ("makemigrations", "migrate", "<others>"): return do-code-that-blows-up #gets run at import urls.py time. setup_at_startup() ... What's a good portable way to test for this, including Django being accessed via gunicorn or the like? -
How do I run Django test using a CustomUser(AbstractUser) class instead of default AbstractUser for correct ForeignKey assignment during test?
I have a CustomUser model in 'accounts' app that overrides Django's default auth.User: class CustomUser(AbstractUser): age = PositiveIntegerField(null=True, blank=True) user_type = CharField(max_length=8, null=False, choices=[('customer', 'Customer'), ('owner', 'Owner')]) And another app 'ecommerce' with a model Product (abbreviated for brevity) with a ForeignKey to the CustomUser field above: class Product(Model): name = CharField(max_length=255, null=False, blank=False) [...] seller = ForeignKey(CustomUser, on_delete=CASCADE, related_name='products') When I create the new Product, I'm using form_valid() function on the model to set the user based on the request that Django uses via CreateView. This works when I'm working in a browser, however does not when I am trying to validate my ProductCreateView through a test a script: views.py class ProductCreateView(CreateView): model = Product [...] def form_valid(self, form): form.instance.seller = self.request.user return super().form_valid(form) test.py def test_product_create_view(self): response = self.client.post( reverse('ecommerce_post_product'), { 'name': 'newProduct', 'price': 2.99, 'category': 'newCategory', 'quantity': 100, 'shipping': 'standard', }) # error happens here self.assertEqual(response.status_code, 302) # test does not reach this line When I run my tests, this test always throws an error stating, ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7fbce54f0040>>": "Product.seller" must be a "CustomUser" instance." I have tried passing in the self.user that I defined in the 'setUp()' function of the TestCase with … -
Django fetch FK data
Hello I am trying to replicate this raw sql query with Django ORM. SELECT G.ID, G.DEFAULT_VAL, G.tag_flg,M.TRANSLATION_ID, M.language_id FROM translation.GLOSSARY G LEFT JOIN translation.GLOSSARY_TRANS_MAP M ON M.GLOSSARY_ID = G.ID and M.LANGUAGE_ID = {language_id} LEFT JOIN translation.GLOSSARY_TRANSLATION T ON T.ID = M.TRANSLATION_ID The models that I have are these: class ReportLanguage(models.Model): iso_cd = models.CharField(max_length=50) display_nm = models.CharField(max_length=50) class Meta: managed = False db_table = 'report_language' class Glossary(models.Model): placeholder = models.CharField(max_length=50) default_val = models.CharField(max_length=150) tag_flg = models.BooleanField() class Meta: managed = False db_table = 'glossary' class GlossaryTransMap(models.Model): glossary = models.ForeignKey('Glossary', models.DO_NOTHING) translation = models.ForeignKey('GlossaryTranslation', models.DO_NOTHING) language = models.ForeignKey('ReportLanguage', models.DO_NOTHING) class Meta: managed = False db_table = 'glossary_trans_map' class GlossaryTranslation(models.Model): translated_val = models.CharField(max_length=1000) crt_dts = models.DateTimeField() crt_user = models.CharField(max_length=255) upd_dts = models.DateTimeField() upd_user = models.CharField(max_length=255) glossary = models.ForeignKey('Glossary', models.DO_NOTHING) translation = models.ForeignKey('GlossaryTranslation', models.DO_NOTHING) class Meta: managed = False db_table = 'glossary_translation' I was able to get similar response as i get from the query with this orm all_glossaries = GlossaryTransMap.objects.select_related('translation', 'glossary', 'language').values( 'glossary__id', 'translation', 'language', default_val=F('glossary__default_val'), tag_flg=F('glossary__tag_flg')).filter(language__id=lang_id) Also the serializer that i created looks like this: class AllGlossariesData(serializers.ModelSerializer): id = serializers.SerializerMethodField() default_val = serializers.SerializerMethodField() tag_flg = serializers.SerializerMethodField() translation_id = serializers.SerializerMethodField() language_id = serializers.SerializerMethodField() class Meta: model = GlossaryTransMap fields = ['id', 'default_val', 'tag_flg','translation_id', … -
How to add watermark to video while saving using django
I'm new in django. How to add watermark to video file while saving using django? -
What is the best method for retrieving all objects associated with a foreign key using Django rest_framework?
I have a React application where I'm using Django+REST for the API and backend. On the frontend, I send a POST request to create a Job model and run the job. In the response, I retrieve the ID of the new Job object. axios.post('http://127.0.0.1:8000/api/jobs/', query) .then((resp) => { setActiveJobs([...activeJobs, resp.data.id]) }, (error) => { console.log(error) }) When the job finishes running, it creates multiple Result objects associated to it by a ForeignKey. These are my two models: class Job(models.Model): query = models.CharField(max_length=255, blank=True, null=True) status = models.CharField(max_length=10, blank=True, null=True) class Result(models.Model): job = models.ForeignKey(Job, blank=False, null=False, on_delete=models.CASCADE) result_no = models.IntegerField(blank=False, null=False) ... more fields I'm having trouble using rest_framework in Django to send a GET request using the Job's ID to get a list of all the Result associated with it. I've tried to give custom implementations for retrieve(self, request, pk=None) and get_queryset(self) but so far my approaches have not worked. Ideally, I'd like to call a url such as localhost:8000/api/results/15 where 15 would be the object id of the Job that was created. If there are 5 Result objects that have the job ForeignKey field set as the Job object with an ID of 15, a list of those … -
Updating a mysql row via Django
I have a basic working app that displays the contents of a table and also allows you to insert new rows. My next step is to allow updating of existing rows, and I'm running into some mental roadblocks that I think are caused by my basic understanding of how components of a django project interact with each other (views,models,templates,etc.). I currently have this views.py file within my "enterdata" app. The "showform" function allows you to create a new record within the db. What I am working on is the "updatedata" function below it, which eventually I would like to have the ability to select a row via the UI and then update. But for now, I am hardcoding the primary key and the value just to get the basics going. I am getting hung up on how I can add an "update" button to my existing HTML template that I'm already using for the ability to create rows. It trips me up that it's not easy to see how a button on an HTML form is mapped to a function in a view. Coming from a Visual Basic background where this was clear, I'm struggling a bit. How can I … -
How to deploy a specific django folder in a repository to an azure app service?
I have a Github repository with the folders back-end and front-end. The folder back-end contains a folder custom-site, which contains a Django project. I would like to use Azure to deploy this Django project, but it seems that Azure only attempts to deploy the root folder of the repository. How do I indicate that the back-end/custom-site/ folder should be used as root? -
how can add the data in db field which already exist
I am trying to add the data in main_storage table but when i save the record it show the error failed unsupported operand type(s) for +: 'DeferredAttribute' and 'int' in Main_Storage productId is foreign key i want to add the data according to the foreign key but it show the error data = self.request.POST.get orderView = GatePass( fault=data('fault'), remarks=data('remarks'), order_id=order_Id ) faultItem = orderView.fault order_request.order.orderProduct.quantity -= int(faultItem) storage = Main_Storage( product_id=productId, quantity=Main_Storage.quantity+order_request.order.orderProduct.quantity ) storage.save() -
Get array of images from JS to Django template
I want to show random images every time someone enters my art gallery or on refresh and change the images on my art gallery every 30 seconds. I have everything set up correctly in Django. In JS I have created a list of jpeg files. I want to pick a random picture. I am not sure how to use the Django syntax {% %} in JS nor do I know if it is possible. There is some code I found and it does something like this: //Add your images, we'll set the path in the next step var images = ['banner-1.jpg', 'banner-2.jpg', 'banner-3.jpg', 'banner-4.jpg]; //Build the img, then do a bit of maths to randomize load and append to a div. Add a touch off css to fade them badboys in all sexy like. $('<img class=" class="fade-in" src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#banner-load'); </script> However, I would like use the Django syntax or something similar so I don't have to specify the path to the images. Also, is there a way to tie this to a timer that will continue to show random pictures for my art gallery? Thanks! -
Cannot resolve keyword 'name' into field. Choices are:
I'm Trying to filter through a model but everytime I tried this error keeps happening: Exception Type: FieldError at /store/dashboard/utiles_dashboard/sliders/ Exception Value: Cannot resolve keyword 'name' into field. Choices are: id, image, order, slider, slider_id here is part of the code: views.py: class SliderListView(SingleTableMixin, generic.TemplateView): """ Dashboard view of the slider list. """ template_name = 'oscar/dashboard/utiles_dashboard/slider_list.html' form_class = SliderSearchForm table_class = SliderTable context_table_name = 'sliders' def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['form'] = self.form return ctx def get_description(self, form): if form.is_valid() and any(form.cleaned_data.values()): return _('Resultado de busqueda de sliders') return _('Sliders') def get_table(self, **kwargs): if 'recently_edited' in self.request.GET: kwargs.update(dict(orderable=False)) table = super().get_table(**kwargs) table.caption = self.get_description(self.form) return table def get_table_pagination(self, table): return dict(per_page=20) def get_queryset(self): """ Build the queryset for this list """ queryset = Slider.objects.all() queryset = self.apply_search(queryset) return queryset def apply_search(self, queryset): """ Filter the queryset and set the description according to the search parameters given """ self.form = self.form_class(self.request.GET) if not self.form.is_valid(): return queryset data = self.form.cleaned_data if data.get('name'): queryset = queryset.filter(name__icontains=data['name']) return queryset Forms.py: class SliderSearchForm(forms.Form): name = forms.CharField(max_length=255, required=False, label=_('Nombre')) def clean(self): cleaned_data = super().clean() cleaned_data['name'] = cleaned_data['name'].strip() return cleaned_data slider_list.html: {% extends 'oscar/dashboard/layout.html' %} {% load i18n %} {% load thumbnail %} {% load static … -
How to remake a function and a loop | Django
When a user places a bid, it is saved in the database and I want to get the info about the bid and display it on the html template. Function: def addprevbid(request, item_id): obj = Bid() obj.user = request.user.username obj.bid = request.POST.get('bid') obj.listing_id = item_id obj.save() item = Listing.objects.get(id=item_id) bidobj = Bid.objects.filter(listing_id = item_id) bid = Bid.objects.filter(bid = item_id) return render(request, "auctions/viewlisting.html", { "item": item, "bids": bidobj, "bid": bid }) Class in models.py class Bid(models.Model): user = models.CharField(max_length=64) title = models.CharField(max_length=64) listing_id = models.IntegerField() bid = models.IntegerField() Loop in html template: <h3>Previous bids:</h3> {% for i in bid %} <h5>{{i.user}}</h5> <h5>{{i.bid}}</h5> {% endfor %} -
Pre-signed URLS on Vultr Object Storage using boto3
I have been working with Vultr for quite a while, and when I wanted to store some media files, I thought of AWS'S S3, and Vultr provides an S3 compatible service (Object Storage). I can use s3cmd CLI to play with the service, and they point to use boto3 for interacting with the S3 service. I wanted to have my objects have signed URLs, but I believe boto3 has amazonaws.com as the hostname as a constant somewhere in the code and that cannot be changed from configs as below in below: import logging from django.conf import settings import boto3 from botocore.exceptions import ClientError from premarket.models import PreMarket from .models import SupervisorLogs class Supervisor(): def __init__(self) -> None: self.bucket_name = settings.BUCKET_NAME self.link_expiration = settings.ONE_WEEK self.queryset = PreMarket.objects.all() # Generate a presigned URL for the S3 object self.s3_configs_object = settings.AWS_S3_CREDS self.s3_client = boto3.client('s3', **self.s3_configs_object) def sign_objects(self): for obj in self.queryset: try: presigned_url = self.create_presigned_url(obj.video_url) obj.presigned_url = presigned_url obj.save() except Exception as e: self.supervisor_logs(level="ERROR", message=e, description=e) logging.error(e) self.supervisor_logs(level="COMPLETE", message="Object URL signing has completed", description="Object URL signing has completed") def create_presigned_url(self, object_name): """Generate a presigned URL to share an S3 object :param object_name: string :return: Presigned URL as string. If error, returns None. """ … -
Vue JS frontend and Django backend
im a begginer in programming and got a task. in general i need to prepare a project with frontend in VueJS3 and backend in Django. i have already built the front end (views, templates etc etc) and it works. the problem is that i need to inject one data from backend. the project is to make a local catering menu let's say. and the menu i need to build in django. i created a superuser and products but i have no idea how to import it to vue. via urls? or other option? i have already looked via the internet but no exact answear. is there any 'shortcut' for it? as i said the front end works good so i dont wanna change it to django now. -
want to remove error message in custom login form in django custom login
i don't want user have to see this message without any error i load page this come automatically here is my views.py def my_login(request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('accounts:home') else: return HttpResponse('<h1>Page was found</h1>') else: return render(request, "login.html", {'form': form}) my forms.py class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("User does not exist.") if not user.is_active: raise forms.ValidationError("User is no longer active.") return super(LoginForm, self).clean(*args, **kwargs) -
Django Celery Heroku - Changed Redis URL enviro variable, but still pointing to old Redis URL
I updated the enviro variable, known as config vars in Heroku for REDDIS_URL I turned off both my app dyno and my worker dyno. I then restarted my app dyno, web gunicorn myapplication.wsgi and have no issues I then restarted my worker worker celery -A myapplication worker -l info --concurrency 2 Which causes me to get the following error in logs [2021-07-06 16:00:05: ERROR/MainProcess] consumer: Cannot connect to redis://OLD_REDDIS_URL Error 111 How do I get the worker to reference the updated config var (enviro variable) for REDDIS_URL? -
How to create a button to change a text in my html with data coming from Django's models.py?
I'm starting to work with Django and I'm starting a test to solidify what I've been learning. The idea is a single page, which displays a sentence as soon as the site opens. Below the phrase, there is a button that I would like to change the phrase to some other phrase coming from a variable declared in models.py and which contains several phrases that were registered through Django's admin panel. This is my models.py file: from django.db import models class Base(models.Model): criado = models.DateField('Criado', auto_now_add=True) modificado = models.DateField('Atualização', auto_now=True) ativo = models.BooleanField('Ativo', default=True) class Meta: abstract = True class Frase(Base): frase = models.CharField('Frase', max_length=100) dica = models.CharField('Dica', max_length=200, default='-') class Meta: verbose_name = 'Frase' verbose_name_plural = 'Frases' def __str__(self): return self.frase This is my views.py file: from django.views.generic import TemplateView from .models import Frase class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['frases'] = Frase.objects.order_by('?').all() return context This is my index.html <div class="container px-4 px-lg-5 h-100"> <div class="row gx-4 gx-lg-5 h-100 align-items-center justify-content-center text-center"> <div class="col-lg-8 align-self-end"> <h1 class="text-white font-weight-bold" id="frase">{{ frases|first }}</h1> <hr class="divider" /> </div> <div class="col-lg-8 align-self-baseline"> <a class="btn btn-primary btn-xl" onclick="nova_frase()">Nova frase</a> </div> </div> </div> (...) <!--rest of the html code--> …