Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I keep getting "false" in my response body, even when the request is successful
My function in my viewset ... def create(self, request): context = {'request':request} serializer = StorySerializer(data=request.data, context=context) if serializer.is_valid(): story = serializer.create(request) if story: return Response(status==HTTP_201_CREATED) else: return Response(status==HTTP_400_BAD_REQUEST) Screenshot of the response a screenshot of my api response -
Heroku error H10 and fwd, my site won't function and I'm unable to determine what actions to take to correct the problem
I just uploaded sync'd my working GitHub repository to Heroku, and when I load the page, I get the "appplication error" page. This is a Django/Python project for school. Here's a bit of the error codes. I've removed my static IP address. 2022-01-20T00:13:48.472109+00:00 app[api]: Starting process with command bash by user studio42dotcom@gmail.com 2022-01-20T00:14:26.576915+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=seitopic.herokuapp.com request_id=731ed097-3b1f-431b-b3bf-04e731125046 fwd="xxx.xxx.xxx.xxx" dyno= connect= service= status=503 bytes= protocol=https 2022-01-20T00:14:30.006905+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=seitopic.herokuapp.com request_id=4029aa01-b304-49d0-ae48-8f5b656a9bc2 fwd="xxx.xxx.xxx.xxx" dyno= connect= service= status=503 bytes= protocol=https About the only thing I can think of that is different was adding in the django-cors-headers, but I don't see how that could be causing issues. The project runs fine locally using python3 manage.py runserver and that doesn't generate errors. The instructors are stumped but said all should be working. I'm not sure what other information you need but I should be able to provide it relatively quickly. -
How to add "-" in django rest_framework Serializer class variables?
I am writing a rest_framework Serializer class for basic validations class ValidateSerializer(serializers.Serializer): client_name = serializers.CharField(allow_blank=False, trim_whitespace=True) and my request data contains "-" in the keys, so I need something like this class ValidateSerializer(serializers.Serializer): # Like the below class variable? I know it is not possible with python variable declaration. client-name = serializers.CharField(allow_blank=False, trim_whitespace=True) I've checked the rest_framework CharField to find out any kwargs that allow me to accept data like client_name = serializers.CharField(name='client-name') So, is it possible to accept - in the Serializer class variables from request data? -
Images in react not displaying
I'm using django and react to build an application. There are some images in react public folder which are being used in different pages. The rest images are coming from django. Both images (images from react and django) were displaying on the browser until I combined react and django and started serving react index.html page from django (using react build folder in django). Immediately I did that the images within react public folder stopped displaying in the browser. The only images I see are those from the API. settings.py BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'media',), os.path.join(BASE_DIR, 'frontend/build/static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), path('api/blog/', include('blog.urls')), ... ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Is there anything I can do to get the images to display? -
How do I export my django model into custom csv?
I have a Django app in which I maintain products for a webshop. Since many products have multiple variations and working in Excel is not optimal, I thought Python could help me and make the work easier. However, for the import into my store system I need a CSV file and here comes my problem. I have a model with five fields where two are multiple fields (django-multiselectfield). SIZES = (('16', 'Size 16'), ('17', 'Size 17'), ('18', 'Size 18'), ('19', 'Size 19'), ('20', 'Size 20')) COLORS = (('white', 'White'), ('black', 'Black'), ('blue', 'Blue'), ('red', 'Red'), ('yellow', 'Yellow')) class Items(models.Model): name = models.CharField(_('Name'), max_length=254, null=True, blank=True, default='',) sku = models.CharField(_('SKU'), max_length=254, null=True, blank=True, default='',) size = MultiSelectField(_('Size'), choices=SIZES) color = MultiSelectField(_('Color'), choices=COLORS) price = models.DecimalField(_('Price'), max_digits=7, decimal_places=2) I created two products to demonstrate my needs In my CSV file, for example, I need a new line for each size and color so that the variation is created correctly in the webshop software. So my CSV would have to look like this: "type","sku","attribute 1 name","attribute 1 value","attribute 2 name","attribute 2 value" "variable","abc01921","size","16","color","white,black,blue" "variation","abc01921_white_16","size","16","color","white" "variation","abc01921_black_16","size","16","color","black" "variation","abc01921_blue_16","size","16","color","blue" "variable","abc01831","size","16,17","color","black,blue" "variation","abc01831_black_16","size","16","color","black" "variation","abc01831_blue_16","size","16","color","blue" "variation","abc01831_black_17","size","17","color","black" "variation","abc01831_blue_17","size","17","color","blue" How do I best implement this successfully? How can I check if … -
Django Rest Framework Ordering on a SerializerMethodField with pagination
How could i sort data based on nested custom serializer method: here is my serializer: class MyModelSerizalier(serializers.ModelSerializer): monthly_price = serializers.SerializerMethodField() class Meta: model = MyModel def get_monthly_price(self, instance): # ... do some calcs with instance # and values that is not related with MyModel installments = [{"due_date": "some_date", "value": 10}] total_price = sum([x["value"] for x in installments]) return {"installments": installments, "total_price": total_price} on my view i have: class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer http_method_names = ['get'] filterset_class = MyModelFilterSet pagination_class = StandardResultsSetPagination # tryed to use same logic for joins but didn't work ordering = ('monthly_price__total_price', '-monthly_price__total_price') ordering_fields = ('monthly_price__total_price', '-monthly_price__total_price') def get_queryset(self): self.queryset also tried this suggestion here but as i'm using pagination, could get the entire response.data to manually sort. any help will be appreciated -
Deploy django project with apache
/etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /home/myuser/project ErrorLog /home/myuser/error.log CustomLog /home/myuser/access.log combined Alias /media/ /home/myuser/project/cdn/cdn_medias/ Alias /static/ /home/myuser/project/cdn/cdn_assets/ <Directory /home/myuser/project/cdn/cdn_assets> Require all granted </Directory> <Directory /home/myuser/project/cdn/cdn_medias> Require all granted </Directory> <Directory /home/myuser/project/project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/myuser/project> Require all granted </Directory> WSGIDaemonProcess project python-path=/home/myuser/project python-home=/home/myuser/myvirualenv/lib/python3.8/site-packages/ WSGIProcessGroup project WSGIScriptAlias / /home/myuser/project/project/wsgi.py </VirtualHost> and /home/myuser# ls access.log project myvirualenv error.log mysql.cnf Why I can not see website on example.com/project or example.com? -
How do I pass a django auth token to view or serializer?
I am trying to work with a Token provided by 'rest_framework.authentication.TokenAuthentication', I would like to either work with the token from the view or from the serializer. What method do I use to make a token viewable inside of my application? Here is what i have tried only the current user returns. The 'auth' key returns none. def get(self, request, format=None): content = { 'auth': str(request.auth), 'user': str(request.user), } return Response(content) -
"Type 'manage.py help ' for help on a specific subcommand" - Error solving python with IIS
I'm trying to run a django project with IIS on Windows server, I've already modified handler mapings and FastCGI Settings -> image statusIt should be running at this point. There's any error but the page is not running. (even withouth /manage.py is the same legend) Legend: "Type 'manage.py help ' for help on a specific subcommand. Available subcommands: [auth]changepasswordcreatesuperuser [channels]runworker [contenttypes]remove_stale_contenttypes [django]checkcompilemessagescreatecachetabledbshelldiffsettingsdumpdataflushinspectdbloaddatamakemessagesmakemigrationsmigratesendtestemailshellshowmigrationssqlflushsqlmigratesqlsequenceresetsquashmigrationsstartappstartprojecttesttestserver [sessions]clearsessions [staticfiles]collectstaticfindstaticrunserver " Any ideas? Thank you -
How to allow CORS from chrome extension origin on django after set white list to all?
I'm trying to re-add CSRF token protection to an API made with Django and deployed to heroku. Local tests with the CSRFToken verification allowed worked fine before I uploaded the web app to heroku but now that I'm in the final tests is not working unless I add the csrf_exempt decorator to the the Django view. I obtained the following error with Django 3.1.7: Referer checking failed - no Referer I was using Django 4.0 on heroku and I decided to try with 3.1.7 version because I tought it could resolve my problem since in this question I understood that this was because in previously Django versions CSRF domain was not checked: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed does not match any trusted origins and I already tried to allow all origins this way (I already use django-cors-headers library): In settings.py: CSRF_TRUSTED_ORIGINS = ['*'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True All of this with the same error: 2022-01-19T23:01:08.715032+00:00 heroku[router]: at=info method=POST path="/smoke/add/" host=my-app.herokuapp.com request_id=b1342451-1a4b-4a0c-9993-ba1e86f0f969 fwd="187.168.154.155" dyno=web.1 connect=0ms service=19ms status=403 bytes=3009 protocol=https 2022-01-19T23:01:08.714194+00:00 app[web.1]: Forbidden (Origin checking failed - chrome-extension://nfbjppodghgcapmokljafeckhkmbcogd does not match any trusted origins.) I don't understand what this is happening … -
Site matching query does not exist. Django/Heroku
My site appears to deploy correctly on heroku, I can access the main page fine but when I try to login or signup (which directs to a new page) I get the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/debug.py", line 90, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/allauth/account/views.py", line 146, in dispatch return super(LoginView, self).dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/allauth/account/views.py", line 74, in dispatch response = super(RedirectAuthenticatedUserMixin, self).dispatch( File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/allauth/account/views.py", line 90, in get response = super(AjaxCapableProcessFormViewMixin, self).get( File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/edit.py", line 135, in get return self.render_to_response(self.get_context_data()) File "/app/.heroku/python/lib/python3.9/site-packages/allauth/account/views.py", line 177, in get_context_data site = get_current_site(self.request) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/sites/shortcuts.py", line 13, in get_current_site return Site.objects.get_current(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/sites/models.py", line 58, in get_current return self._get_site_by_id(site_id) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/sites/models.py", line 30, in _get_site_by_id site = self.get(pk=site_id) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 439, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /accounts/login/ Exception Value: Site matching query does … -
Using subdomains for redirection only (Special for Django)
Suppose that my domain is example.com I want to set subdomains such as blog.example.com, contact.example.com ... In my use case: The subdomains will never have unique content. They will always redirected to determined URLs. Assume that, --> Site objects were created for them. (using The “sites” framework) site_1 : example.com site_2 : contact.example.com site_3 : blog.example.com ... --> Then, Redirects are handling with The Redirects app. Example Redirects Goals: >>> redirect_1 = Redirect.objects.create( ... site_id=1, ... old_path='/contact-us/', ... new_path='/contact/', ... ) >>> redirect_2 = Redirect.objects.create( ... site_id=2, ... old_path='/', ... new_path='https://example.com/contact/', ... ) >>> redirect_3 = Redirect.objects.create( ... site_id=3, ... old_path='/first-blog/', ... new_path='https://example.com/blog/first-blog/', ... ) My questions - Can The sites framework and The redirects app be used this way with subdomains? - If possible, how should subdomains be configured for this use case? Note: Assume that there is no configuration related to subdomains in the project and that what is wanted to be done is prefer to done by Django side as much as possible. -
Django: Reverse for 'update-gig' with arguments '('',)' not found. 1 pattern(s) tried: ['freelance/gig/(?P<gig_category_slug>[
I want to put a url in the update button it not working out rather throwig an error update.html <a href="{% url 'freelance:update-gig' gig.gig_category_slug %}"> Update </a> views.py @login_required def update_gig(request, gig_category_slug): user = request.user gig = get_object_or_404(Gigs, slug=gig_category_slug) freelancer = Freelancers.objects.get(user=request.user) if request.method == "POST": form = CreateGig(request.POST, request.FILES, instance=gig) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user new_form.creator = freelancer new_form.slug = slugify(new_form.title) new_form.save() messages.success(request, f'Gig Updated Successfully!') return redirect('freelance:gig-details', slug=gig_category_slug) else: form = CreateGig(instance=gig) context = { 'form': form } return render(request, 'freelance/create.html', context) -
Django channels - unable to subscribe to groups
I'm attempting to send consumers.py information to display on the client end outside of consumers.py. I've referenced Send message using Django Channels from outside Consumer class this previous question, but the sub process .group_send or .group_add don't seem to exist, so I feel it's possible I'm missing something very easy. Consumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class WSConsumer(WebsocketConsumer): def connect(self): async_to_sync(self.channel_layer.group_add)("appDel", self.channel_name) self.accept() self.render() appAlarm.py def appFunc(csvUpload): #csvUpload=pd.read_csv(request.FILES['filename']) csvFile = pd.DataFrame(csvUpload) colUsernames = csvFile.usernames print(colUsernames) channel_layer = get_channel_layer() for user in colUsernames: req = r.get('https://reqres.in/api/users/2') print(req) t = req.json() data = t['data']['email'] print(user + " " + data) message = user + " " + data async_to_sync(channel_layer.group_send)( 'appDel', {'type': 'render', 'message': message} ) It's throwing this error: async_to_sync(channel_layer.group_send)( AttributeError: 'NoneType' object has no attribute 'group_send' and will throw the same error for group_add when stripping it back more to figure out what's going on, but per the documentation HERE I feel like this should be working. -
How to serve a subdomain and the domain on a single django-cms?
Is is possible to serve a subdomain and the main domain on the same django-cms instance ? For example: how to serve the following submains and the main domain on the same Django-CMS instance ? abc.mydomain.com xyz.mydomain.com www.mydomain.com If so, what are needed to be done in Apache httpd.conf and Django-CMS ? Thank you in advance. -
Sending dictionary as Django model attribute
Is there any possibility to send some keyword: argument into django model attribute (one attribute)? I tried to use models.TextField for that but there must be better solution. from django.db import models class Newsletter(models.Model): start_datetime = models.DateTimeField() text = models.TextField(blank=True) filter = models.TextField() end_datetime = models.DateTimeField() -
validators for bulk image upload
I have setup a validator for a image upload field to check if the image is too large, it is working as expected. def validate_image(image): file_size = image.file.size if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError(f'Image {image} is too large 3mb max') image = models.ImageField(default='default.jpg', storage=PublicMediaStorage(), upload_to=path_and_rename, validators=[validate_image]) Now I want to do the same thing for a bulk image upload field I have. def validate_image_bulk(images): file_size = images.file.size if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError(f'Image {images} is too large 3mb max') images = models.ImageField(upload_to=path_and_rename_bulk, validators=[validate_image]) If you upload more than one image and one of the images is above the max upload threshold it does not upload any of the images and does not throw the validation error but it still submits the form. If you upload a single image that is too large the same thing occures How can I raise the validation error and not have the form submit like it does for the single image field view: (the bulk model is PostImagesForm) postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if len(request.FILES.getlist('images')) > 30: raise Exception("Max of 30 images allowed") else: if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() if len(request.FILES.getlist('images')) == 0: return redirect('post-detail', … -
How to index Image url in elasticsearch using django
I am trying to index an Image url to elasticsearch in but I keep on failing. And I recieve photo_main = null in my search responses. anyone have an idea how it should be done? below is my relevant code, I summarized it as far as possible. thanks in advance model.py class Recipe(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) photo_main = models.ImageField(upload_to='media/', blank=True) title = models.CharField(max_length=150) instructions_text_list = ArrayField(models.CharField(max_length=100,),default=list, size=15,) ingredients_text_list = ArrayField(models.CharField(max_length=100,),default=list, size=15,) def get_absolute_url(self): """Return absolute URL to the Recipe Detail page.""" return reverse('recipes:detail', kwargs={"pk": self.id}) def __str__(self): return self.title documents.py from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from elasticsearch_dsl import analyzer, tokenizer from .models import Recipe autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'edge_ngram', min_gram=1, max_gram=20), filter=['lowercase'] ) @registry.register_document class RecipeDocument(Document): title = fields.TextField(required=True, analyzer=autocomplete_analyzer) ingredients_text_list = fields.ListField(fields.TextField()) instructions_text_list = fields.ListField(fields.TextField()) photo_main = fields.FileField() class Index: name = 'recipes' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, 'max_ngram_diff': 20 } class Django: model = Recipe fields = [ 'id', ] -
Djanog display user specific objects
I solved the last problem. Now I tested some stuff and got a problem. I want to display user specific objects. If user a user enters his details (for example number), I just want to display the phone number of the user in the html template, not from someone else. So the user can only see his number. I created this. forms.html <form method='POST' action="." enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type='submit' class=''>Submit</button> </form> <p>{% if details.phone %} {{details.phone}} {% else %} &nbsp; {% endif %} </p> <p> {{ request.user }} </p> views.py def edit_profile(request): details = UserProfile.objects.all()[0] try: profile = request.user.userprofile except UserProfile.DoesNotExist: profile = UserProfile(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('/') else: form = UserProfileForm(instance=profile) return render(request, 'forms.html', {'form': form, 'details': details}) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True) phone = models.CharField(max_length=10, blank=True) address = models.CharField(max_length=1024) age = models.PositiveIntegerField(blank=True, null=True) gender = models.IntegerField(default=1) The {{ request.user }} works fine, it shows the current username of the signed in user. And with {{ details.phone }} I want to just display the number the user entered in the phone field. But currently it is displaying the number of … -
django alter css style width on progress bar
I have a progress bar, with style width set in css, is there a way to update that style width with some logic in django, and how? <div class="progress-bar bg-warning" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div> Now lets say that i want a more dynamic update on the width? -
how to popup form with django formset
i've have application in the home page there shows some posts with a contact form, i want to create a modal formset in another view! is it possible please ? @login_required def addPopupVistor(request): formset = VistorFormSet(queryset=Vistor.objects.none(),prefix='formsetvisitor') if request.is_ajax() and request.method == 'POST': formset = VistorFormSet(request.POST,prefix='formsetvisitor') if formset.is_valid(): for form in formset: obj = form.save(commit=False) if form.cleaned_data !={}: obj.admin = request.user obj.save() return JsonResponse({'success':True}) else: return JsonResponse({'success':False,'error_msg':formset.errors}) return render(request,'main/home.html',{'formsetvisitor':formset}) const addNewFormRow = document.getElementById('addPopUpButton') const totalNewPopUpForms = document.getElementById('id_formsetvisitor-TOTAL_FORMS') addNewFormRow.addEventListener('click',add_new_popuprow); function add_new_popuprow(e){ if(e){ e.preventDefault(); } const currentFormPopUpClass = document.getElementsByClassName('popup_modal_formset') const countpopupForms = currentFormPopUpClass.length const formCopyPopupTarget = document.getElementById('visitorform') const empty_form = document.getElementById('empty_popup_formset').cloneNode(true); empty_form.setAttribute('class','relative p-2 bg-gray-900 bg-opacity-25 border border-gray-900 rounded-xl pb-14 popup_modal_formset') empty_form.setAttribute('id',`form-${countpopupForms}`) const rgx = new RegExp('__prefix__','g') empty_form.innerHTML = empty_form.innerHTML.replace(rgx,countpopupForms) totalNewPopUpForms.setAttribute('value',countpopupForms + 1) formCopyPopupTarget.append(empty_form) } <button onclick="modal()" class="some css class">add new guest</button> <div id="modal" class="w-full fixed top-0 md:overflow-y-scroll hidden flex flex-wrap p-1 h-screen justify-center items-center bg-black opacity-90" style="z-index: 99999;"> <div class="w-full md:w-10/12 p-2 bg-white rounded-xl"> <button id="addPopUpButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl"> {% trans "add new form" %} <i class="fas fa-plus"></i> </button> <form method="POST" class="mt-2" id="addnewguests">{% csrf_token %} {{formsetvisitor.management_form}} <div id="visitorform" class="grid md:grid-cols-3 gap-16 md:gap-x-3 md:gap-y-8"> {% for form in formsetvisitor.forms %} {{ form.pk }} {{form}} <!-- first form --> <div class="relative … -
django project creation, could not find django.core.managment error
Everytime I create a new django project. I get an error message as shown below: Import "django.core.management" could not be resolved from source Pylance(reportMissingModuleSource)[11,14] Below is the steps I use to create django project: create folder go to the folder. Activate virtual environment using pipenv shell pipenv install django (... and other dependencies) while virtual environment mode is enabled, I do: django-admin startproject projectname When I do above. I get an error as shown. I try again, same problem. I am a newbie, so a detailed explanation would be greatly appreciated! below is the manage.py, where the source of error is coming from: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testapp.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
PGADMIN4 with DJANGO on google cloud 404 error
ok I can see the files. I can use the database. Apparently its running: (myprojectenv) michael@contra:~/myproject$ sudo systemctl status postgresql ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled) Active: active (exited) since Sun 2022-01-16 23:51:55 UTC; 2 days ago Main PID: 22981 (code=exited, status=0/SUCCESS) Tasks: 0 (limit: 613) Memory: 0B CGroup: /system.slice/postgresql.service However, when I go to contra.nz/pgadmin4 Django takes over and is looking for a page. How do I access PGADMIN4 without uninstalling DJANGO :( -
How can I use a url parameter(that is a user id <str:pk>) to prepopulate a field in DJANGO form
I'm doing a management application with 2 pages: users(clientes) and a user datail page that contains a user payment history(cheques). I'm trying to do a create a form in payment history page(cheques.html) to add a new payment, but I'd the Cheque.cliente would be equals to the current user URL. Ex.: if your URL is cheque/5/, the Cheque.cliente should be 5, and when I add a new payment, the payment should be tracked(ForeignKey) to the user 5(each user has many payments). Resuming: This application has the functions to CRUD all the user(clientes) and all the payments(cheques), but only the add payment(cheque) function isn't working. VIEWS.py #CLIENTES def index(request): clientes = Cliente.objects.all() form = ClienteForm() if request.method == 'POST': form = ClienteForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'clientes':clientes, 'form':form} return render(request, 'clientes/home.html', context) #CHEQUES #THE ERROR IS IN THIS VIEW! def chequesCliente(request, pk): cheques = Cheque.objects.filter(id=pk) nome = Cliente.objects.get(id=pk) formc = ChequeForm() if request.method == 'POST': formc = ChequeForm(request.POST) print(formc.data['cliente']) if formc.is_valid(): print(formc.cleaned_data) formc.save() return redirect('/') context = {'cheques':cheques, 'formc':formc, 'nome':nome,} return render(request, 'clientes/cheques.html', context) def updateCheque(request, pk): cheque = Cheque.objects.get(id=pk) formc = ChequeForm(instance=cheque) if request.method == 'POST': formc = ChequeForm(request.POST, instance=cheque) if formc.is_valid(): formc.save() return redirect('/') context = {'formc':formc} … -
Django Password Reset Email sending incorrect link
I am using the auth_views login and password reset system for the accounts app in a Django project. The password reset functionality works fine on the localhost. However once deployed when trying to reset the password the email that is sent to the user's registered email account contains the incorrect reset URL. The domain part of the reset URL contains the localhost address and not the domain of the site. The email is sent to a link like http://127.0.0.1:8000/accounts/reset/MTk/azifmz-484db716de96c7628427b41e587c1910/[![enter image description here]1]1 What I am expecting is for the sent email to contain the correct return URL specific to the domain that is sending it. e.g https://www.example.com/accounts/reset/MTk/azifmz-484db716de96c7628427b41e587c1910. In settings.py LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = 'index' STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST= 'smtp.gmail.com' EMAIL_HOST_USER= 'myemail@gmail.com' EMAIL_HOST_PASSWORD= 'mypassword' EMAIL_USE_TLS= True EMAIL_PORT= 587 In my accounts urls.py I am using the default classed bassed views provided by django.contrib.auth. There are no custom views for the reset workflow. I am hoping to configure this workflow to avoid having to write custom views for now. urls.py path('password_reset/', auth_views.PasswordResetView.as_view( template_name="accounts/password_reset_form.html", success_url="done/"), name="password_reset"), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view( …