Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Static file not loading ImageField URL
This is for an assignment, we need to store the images in the static directory and display them on a template. The images are stored through the item model ImageField and uploaded to the static/images directory. Here is the template code: {% load static %} <p><a href='..'>Home</a></p> {% block content %} <table> <tr> <th>Item Name</th> <th>Manufacturer</th> <th>Cost</th> <th>Weight</th> <th>Image</th> </tr> {% for i in name %} {% if i.name == params %} <tr> <td>{{i.name}}</td> <td>{{i.manufacturer}}</td> <td>{{i.cost}}</td> <td>{{i.weight}}</td> <td><img src="{% static i.image.url %}" alt="{{i.image.url}}"></img></td> </tr> {% endif %} {% endfor %} </table> {% endblock %} I have the following model code: from django.db import models class item(models.Model): name = models.CharField(max_length=40) manufacturer = models.CharField(max_length=255) cost = models.DecimalField(max_digits=10, decimal_places=2) weight = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='static/images/') Here are the current settings import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'Nice try' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite', ] … -
My comments aren't displaying on the HTML page
Hey guys I'm building an auction site and for some reason my comments (a dict called commentQuery) is not displaying on the HTML page. Anyone see why? I'm sure it's something minor I'm missing. Thanks! relevant code below: views.py: def comment(request): username = request.POST.get("username") itemID = request.POST.get("itemID") comment = request.POST.get("comment") new = Comment.objects.create(username = username, comment = comment, itemID = itemID) new.save() commentQuery = Comment.objects.all() return render(request, "auctions/post.html", { "commentQuery": commentQueries}) post.html: <form name="comment" action="/comment" method="post"> {% csrf_token %} <h2>Comments</h2> {% if user.is_authenticated %} <input autofocus class="form-control" type="text" name="comment" placeholder="Enter Comment"> <input autofocus class="form-control" type="hidden" name="itemID" value={{p.title}}{{p.price}}> <input autofocus class="form-control" type="hidden" name="username" value={{user.username}}> <input class="btn btn-primary" type="submit" value="Add Comment"> {% endif %} </form> {% for commentQuery in commentQueries %} <li>{{ commentQuery.comment }} by {{ commentQueries.username }}</li> {% endfor %} {% endblock %} -
append dict to list without duplicate python django
i have this object data_listmedia print(data_listmedia) : [{'id': 6, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 400, 'nomberhodor': 30, 'date': datetime.date(2020, 9, 25)}, {'id': 7, 'withdegrey_id': 2, 'withsecondray_id': 2, 'nomberesteda': 400, 'nomberhodor': 200, 'date': datetime.date(2020, 9, 25)}, {'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}] so now i want append this persontage dict to all dicts in this list so i use this loop : first i declared mydict ={} data = [] for l in data_listmedia: persontage = ((l["nomberhodor"] * 100) / l["nomberesteda"]) mydict.update({"percontage": persontage}) data.append(mydict) mydict.update(l) but when finsh the loop its apeend thelast dict in list print(data) = [{'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}, {'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}, {'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}] why when use data.append(mydict) its duplicate the last dict in the all list but when i use print(persontage) inside the loop the value come true 7.5 50.0 60.0 how i can append dict to list without duplicate -
how to list employee under loggedin manager in Django
i wanted to list employee under manager(only for manager who login) https://github.com/dineshdk13/Employeesite.git -
How do I make a custom form errors section in my Django template?
In my Django template I can show errors using this syntax {{ form.errors }}. But that evaluates to this html syntax in my template: <ul class="errorlist"> <li>password <ul class="errorlist"> <li>Ensure this value has at least 10 characters (it has 2).</li> </ul> </li> <li>confirm_password <ul class="errorlist"> <li>Ensure this value has at least 10 characters (it has 2).</li> </ul> </li> <li>first_name <ul class="errorlist"> <li>Ensure this value has at least 2 characters (it has 1).</li> </ul> </li> <li>last_name <ul class="errorlist"> <li>Ensure this value has at least 2 characters (it has 1).</li> </ul> </li> </ul> This is not the html syntax I want. I actually want to wrap them in my own elements. For example {%if form.errors %} <section class="errors-container"> {% for err in form.errors %} <p>{{err.field_name}}</p> <div> {{err.actual_error_for_field_name}} </div> {% endfor %} </section> {%endif%} That is the layout I want. I even tried passing an errors variable to the context dictionary in my view. def user_register(request): errors = {} if request.method == 'POST': form = PersonRegisterForm(request.POST) if form.is_valid(): if form.cleaned_data['password'] == form.cleaned_data['confirm_password']: cd = form.cleaned_data new_user = Person.objects.create_user(username=cd['username'], email=cd['email'], password=cd['password'], first_name=cd['first_name'], last_name=cd['last_name']) messages.success(request, f'You are successfully registered as {new_user.username}!') return redirect("profile", new_user.id) for i in form.errors: errors[i] = form.errors[i] print(errors) else: form = … -
Django change value before save in ModelViewSet
I am new to Django (and the REST framework) but I am struggling to update a value before save. Right now I am using a simple ModelViewSet to update a record. Everything works, but the value doesnt get updated if I create an item in de admin site. Code of the view is as follows: class OauthProviderViewSet(viewsets.ModelViewSet): queryset = OauthProvider.objects.all() serializer_class = OauthProviderSerializer authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAdminUser] def perform_create(self, serializer): changed_credentials = "test" + self.request.credentials serializer.save(credentials=changed_credentials) I just want to pre-pend the word test to the credentials field. -
Django REST Framework: Creating Object and Connecting Foreign Key with Serializers
Currently, my TaskList objects are connected to my TaskItem objects by a foreign key (with the TaskItems being in a list called task_items). I am able to add items in the shell to the list fine, but when it comes to the serializer I haven't been able to figure out how to connect these two entities. The request.data object and the serializer.data object are not compatible to work with the DB API commands. Is this possible to do? If so, what would be the best way to go about this? models.py class TaskItem(models.Model): task_name = models.CharField(max_length=200) difficulty_level = models.IntegerField(default=1) def __str__(self): return self.task_name class TaskList(models.Model): list_name = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) task_items = models.ManyToManyField(TaskItem) def __str__(self): return self.list_name serializers.py class TaskSerializer(serializers.ModelSerializer): class Meta: model = TaskItem fields = '__all__' class TaskListSerializer(serializers.ModelSerializer): TaskItem = TaskSerializer() class Meta: model = TaskList fields = '__all__' # list_name, user, task_items views.py @api_view(['POST']) def addTask(request, pk): user = User.objects.get(id=pk) taskList = TaskList.objects.select_related().filter(user=user).first() taskListSerializer = TaskListSerializer(taskList) serializer = TaskSerializer(data=request.data) if serializer.is_valid() and taskListSerializer.is_valid(): serializer.save() return Response(serializer.data) -
How to make nested jsonb model with django / postgres?
The model I want to make is similar to the youtube api model. { "videos": [ { "id": "7lCDEYXw3mM", "snippet": { "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw", "title": "Google I/O 101: Q&A On Using Google APIs", "categoryId": "28" }, "statistics": { "viewCount": "3057", "likeCount": "25", "dislikeCount": "0", "favoriteCount": "17", "commentCount": "12" } } ] } I tried using ArrayField but when I posted a list of fields into the array I kept getting this error: "Expected a list of items but got type \"dict\"." This is the model so far class Menu(models.Model): burgers = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, default=None ) beverages = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, default=None ) extras = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, default=None ) fries = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, default=None ) I want to make each item inside the Array to have its own fields for the name and price. { "burgers": [ 0:{ "name":"Plain patty", "price":4 }, 1:{ "name":"Cheese buns", "price":8 } ] } How can I make it with jsonb? -
How can i check if the function based view was called from another redirect function or directly from the url?
I have an online store where users pay at domain.com/pay and receive their product after paying at domain.com/done However, when I was testing it I found out that users can go to the URL and type domain.com/pay manually and all a sudden, they get their product without paying! I want someway to check whether the user accessed it manually or from a redirection, if manually then raise http403 if from redirect then the function will happen normally Here is my process_pay view def payment_process(request, trade_id): trade = get_object_or_404(Trade, id=trade_id) host = request.get_host() paypal_dict = { 'business': trade.seller.email, 'amount': Decimal(trade.price), 'item_name': trade.filename, 'invoice': str(trade.id), 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'http://{}{}/{}'.format(host, *reverse('payment_done', kwargs={'trade_id': trade.id})), 'cancel_return': 'http://{}{}'.format(host, reverse('home')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/payment_process.html', {'trade': trade, 'form': form}) my done_process view @csrf_exempt def payment_done(request, trade_id): # if user entered from a redirection: # Give product to user # elif user entered manually: raise http403 # else: messages.error(request, 'something went wrong') return redirect('home') return redirect('trade:inbox') -
Filter api view from another view result Django (REST)
I have 2 API returned in Django like this. List of apps: {"count":3,"next":null,"previous":null,"results":[ {"id":1,"user":"x","name":"app1","title":"title1","active_user":"user1"}, {"id":2,"user":"x","name":"app2","title":"title2","active_user":"user1"}, {"id":3,"user":"x","name":"app3","title":"title3","active_user":"user1"}]} This API have X ids or name (only 3 here for the example), imagine 100 or more. They must match with the second API (field id or name of list_apps). And the second has already been filtered for just the active user. User data: {"count":1,"next":null,"previous":null,"results":[ {"user":"user","email":"none","list_apps":{ "1":{"id":"1","hgt":"1","pos":"1","wth":"1","name":"hello","color":"default","visible":"true"}, "2":{"id":"2","hgt":"1","pos":"2","wth":"1","name":"dash","color":"default","visible":"true"}, So, in this case, I expected to return only the 2 first app in the first API (list of app), because the user have only access to 1 and 2. (list_apps are from a PostGre JSON field). Answer expected: {"count":3,"next":null,"previous":null,"results":[ {"id":1,"user":"x","name":"app1","title":"title1","active_user":"user1"}, {"id":2,"user":"x","name":"app2","title":"title2","active_user":"user1"}]}, Here's the view.py @permission_classes([IsAuthenticated]) class DashListCreate(generics.ListCreateAPIView): renderer_classes = [JSONRenderer] serializer_class = DashSerializer def get_queryset(self): return Dash.objects.filter(id__in=["1","2","3"]) @permission_classes([IsAuthenticated]) class UserDashListCreate(generics.ListCreateAPIView): renderer_classes = [JSONRenderer] serializer_class = UsersDashSerializer def get_queryset(self): print(UsersDash.objects.only('list_apps').values()) return UsersDash.objects.filter(user=self.request.user) The answer is maybe replace the field ["1","2","3"] in the filter by the list of "id" in the other api : list_app.api.all() but i don't know 2 things : How to call an API from Another Just select the values I need, I tried only('list_apps').values() but it does not work (no filter). Is it a good practice to filter in the view or there … -
Django - Is this solution DRY or is there a better way to model these profile classes and subclasses?
Basically, I have the following requirements: A user has a personal user profile An organisation can have a staff profile The staff profile can be independent or link to a user The organisation can edit the staff profile without changing the users' personal user profile A user changing their personal user profile wouldn't affect an organisations staff profile of the user A user can be staff at multiple organisations (and hence have multiple staff profiles) A user doesn't have to be staff Currently I have the following classes (Irrelevant fields removed for simplicity) profiles.models.py class Profile(TimeStampMixin): title = models.CharField(max_length=6, choices=Title.choices, blank=True) forename = models.CharField(max_length=50, blank=True) surname = models.CharField(max_length=50, blank=True) class UserProfile(Profile): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name="profile", on_delete=models.CASCADE) class StaffProfile(Profile): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, db_index=True, related_name="staff_profiles") organisations.models.py class Organisation(TimeStampMixin): staff = models.ManyToManyField('profiles.StaffProfile', blank=True, related_name="organisations") What I'm wondering is whether this solution is DRY and whether it's the best way of dealing with the requirements? The reason I'm not sure is because I've contemplated having StaffProfile extend UserProfile instead of Profile and changing the OneToOneField in UserProfile to a ForeignKey Field however this seems like it would complicate finding a User's personal profile from their staff profile. Unless I change the related_name … -
Postgres procedure not updating selected row
I'm working on a Django application that uses Stored Procedures on a PostgreSQL database. I'm stuck in a very strange (for me, at least) problem. I have the following SP code: create procedure inbound_550(p_operation_id integer) language plpgsql as $$ declare file_operation record; ... begin select oo.id, oo.file_id, ot.transaction_type_id, ot.code into file_operation from operations_operation oo join operations_type ot on ot.id = oo.type_id where oo.id = p_operation_id; for line in # select some records from other tables using parameter p_operation_id on some FKs loop # business logic here with some calculations and some inserts sum_tax_day = X # some value end loop; operation_avg_year_tax = ((1 + (sum_tax_day / 100)) ^ 252) - 1; update operations_operation set avg_year_tax = operation_avg_year_tax where id = p_operation_id; end $$; The problem is, when I call this procedure from the console it runs fine and the field avg_year_tax gets updated with the operation_avg_year_tax value but, when I call the procedure from my application using Python and psycopg2 the field is not updated, it seems that the update statement is ignored. Here is the Python code used to call the procedure: from django.db import connection class Inbound: def __init__(self, operation): self.operation = operation def main(self): conn = connection … -
please someone should help me out... this gives me error
views.py @login_required def edit_entry(request, entry_id): """ edit exiting entry """ entry = Entry.objects.get(id=entry_id) blogpost = entry.blogpost check_blog_owner(request, blogpost_id) if request.method != 'POST': # initial request, pre-fill with entry data form = EntryForm(instance= entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('blogs:blogpost', args=[blogpost.id])) context = {'entry':entry, 'blogpost':blogpost, 'form':form} return render(request, 'blogs/edit_entry.html', context) def check_blog_owner(request, blogpost_id): """check if the blog owner is logged it""" blog = BlogPost.objects.get(id=blogpost_id) if blog.owner != request.user: raise Http404 Traceback (most recent call last): File "C:\Users\MUHDYE~1\DOWNLO~1\PROGRA~1\FULL-S~1\Blog\bb_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\MUHDYE~1\DOWNLO~1\PROGRA~1\FULL-S~1\Blog\bb_env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\MUHDYE~1\DOWNLO~1\PROGRA~1\FULL-S~1\Blog\bb_env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Muhd Yekini\Downloads\programming\FULL-STACK projects\Blog\blogs\views.py", line 72, in edit_entry check_blog_owner(request, blogpost_id) Exception Type: NameError at /edit_entry/13/ Exception Value: name 'blogpost_id' is not defined -
SMTPAuthenticationError at /
my django app is not being able to send email. On my email less secure apps is turned on and i have unlocked captcha. am stuck i dont know what am missing. any help will be appreciated. Traceback Environment: Request Method: POST Request URL: http://localhost:8000/ Django Version: 3.0.9 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shield_sec'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/apple/projects/Django/ingabo_sec/shield_sec/views.py", line 17, in contact send_mail ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 734, in login raise last_exception File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 723, in login (code, resp) = self.auth( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 646, in auth raise SMTPAuthenticationError(code, resp) Exception Type: SMTPAuthenticationError at / Exception Value: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials l188sm1732224lfd.127 - gsmtp') settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ … -
How to import django allauth.account when already having an app module named 'account'?
settings.py INSTALLED_APPS = [ 'apps.account', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.linkedin_oauth2', ] error shows : Application labels aren't unique, duplicates: account I cannot change my project app named 'account' also i need to use allauth.account .How can I solve this issue ? -
How to deploy a django-react app to docker container and run it?
I have a Django-backend React-frontend small application and I need it to run on Docker container so I can start both servers with one button/file, I don't have any Docker experience except for understanding core concepts, can someone point me out to a good modern tutorial or just give some instructions on how to do it? -
How can my translation be shown in my website
I am currently working on my website, which is a translator which you input a phrase and it gets translated into an invented language. Here's the code of the translator function: def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation However, I am stuck in showing this funcion in my web, here's the code in views.py: from .translate import translator def translated_view(request): text = request.GET.get('text') print('text:', text) translate = translator dt = translator.detect(text) tr = translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') Here's the template that should would show the translation. {% extends "base.html"%} {% block content%} <div > <center><h2 class = "display-4">DNA TRANSLATED SUCCESFULLY INTO</h2></center> <br> <br> <br> <h3> {{ translated }} </h3> </div> {% endblock content%} -
I can not access to mount directory from Django when using docker
I run Django in docker and I want to read a file from host. I mount a path in host to container using following command in my docker-compose file: volumes: - /path/on/host/sharedV:/var/www/project/src/sharedV Then I execute mongodump and export a collection into sharedV on host. After that, I inspect web container and go to the sharedV directory in container and I can see the backup file. However, when I run os.listdir(path) in django, the result is empty list. In the other word, I can access to sharedV directory in Django but I can not see its contents! Is there any idea that how can I access to host from a running container? thanks -
send metatags through Google Cloud Signed URL with Django
I'm using signed url to get or post/put video fileq on my google storage. My modules refers on signed_url V4 and it's working quite well. I wanted to add some metadata tags to my requests in order to manage more efficiently the charges related to GCS. But since I added those headers, the requests failed returning a cors policy error : (I have shortened the signature in the block above to make it more readable) Access to XMLHttpRequest at 'https://test-dev-slotll.storage.googleapis.com/uploads/dave/FR/eaa678c9/2020/9/785f/f45d3d82-785f_full.mp4?X- Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=dev-storage%40brilliant-tower-264412.iam.gserviceaccount.com%2F20200926%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20200926T093102Z&X-Goog-Expires=3600&X-Goog-SignedHeaders=host%3Bx-goog-meta-account&x-goog-signature=6fbb27e[...]bd0891d21' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. and the detailed message: <Error> <Code>MalformedSecurityHeader</Code> <Message>Your request has a malformed header.</Message> <ParameterName>x-goog-meta-account</ParameterName> <Details>Header was included in signedheaders, but not in the request.</Details> </Error> The cors are conigured to allow almost everything on my bucket : [{"maxAgeSeconds": 3600, "method": ["*"], "origin": ["*"], "responseHeader": ["*"]}] and here is the Python/Django function def _get_signed_url(self, http_method="GET"): """' create a signed url with google storage create a 'GET' request by default, add method='w' or 'put' to create a 'PUT' request get_signed_url('w')->PUT / get_signed_url()->GET """ if http_method.lower() in ["w", "put", "post"]: http_method = "PUT" else: http_method = "GET" signed_url = generate_signed_url( settings.GS_BUCKET_NAME, self.file.name, subresource=None, expiration=3600, http_method=http_method, … -
Django simple captcha and ajax sometimes not workings
I'm used Django-simple-captcha in my Django project. The user submits the wrong captcha while showing error but sometimes the user submit the wrong captcha and show us the account is created successfully (account isn't created). I can't figure out that issue. I thought the problem with ajax. I want --> user submit her details with valid captcha then account created but the user submits the wrong captcha then shows an error message and the page not load. how can I solve this issue? this is my details. views file @is_user_logged_in @find_and_assign_anonymous_cart() def signup(request): if request.region.code.upper() == settings.DEFAULT_LOCAL_COUNTRY: form = LocalSignupForm(request.POST or None) else: form = SignupForm(request.POST or None) if form.is_valid(): human = True form.save() password = form.cleaned_data.get('password') confirm_password = form.cleaned_data.get('confirm_password') email = form.cleaned_data.get('email') _group = Group.objects.get(name='customer') user = auth.authenticate( request=request, email=email, password=password) _group.user_set.add(user) if user: # Get Client IP Address current_user = user client_ip = get_client_ip(request) current_user.last_login_user_ip = client_ip current_user.last_login_user_country = get_country_by_ip(client_ip) current_user.save() if user.groups.filter(name='customer').exists(): request.session['is_customer'] = True # send welcome email, with four featured products # featured_products = products_for_homepage() domain = request.site scheme = request.is_secure() and "https" or "http" domain = "{}://{}".format(scheme, domain) email_tpl_context = { "request": request, "customer_name": email, "domain": domain, # it will be changed to customer … -
Django view-function for personal page of "author"
How to pass information about a specific user and his messages to the view function. For example, I write the following URL: http://127.0.0.1:8000/leo. Leo is the author of posts. I already have a template to display all posts for a specific author. Here is my view function: def profile(request, username): user = posts = return render(request, 'profile.html', {'user': user, 'posts': posts}) Thank's guys -
Server error after deploy a Django project with MediumEditor
I built a blog-like site in Django, and deployed it on Linode. Everything works well if I don't use the Django MediumEditor, but with this app. included I get a server error 500 when trying to get a page that uses such editor. I blindly followed all the instructions on how to use Medium editor with Django; here below all the files that call the editor. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mediumeditor', 'blog.apps.BlogConfig' ] ... MEDIUM_EDITOR_OPTIONS = { 'toolbar': { 'buttons': [ 'bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript', 'link', 'quote' ] }, 'placeholder': {'text': 'insert text'} } blog/admin.py from django.contrib import admin from .models import Post, Comment from mediumeditor.admin import MediumEditorAdmin @admin.register(Post) class PostAdmin(MediumEditorAdmin, admin.ModelAdmin): mediumeditor_fields = ('title', 'content') search_fields = ['title', 'content'] list_display = ['title', 'content', 'date'] list_filter = ['title'] list_editable = ['content'] @admin.register(Comment) class CommentAdmin(MediumEditorAdmin, admin.ModelAdmin): mediumeditor_fields = ('content') blog/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.utils.safestring import mark_safe from .models import Post, Comment from mediumeditor.widgets import MediumEditorTextarea class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=50, required=True) last_name = forms.CharField(max_length=50, required=True) email = forms.EmailField(max_length=100, required=False, help_text="Optional") class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'email') … -
Django set CreateView field programmatically with foreign key SELECT FROM WHERE clause
class Contest(TimeStampedModel): is_open = models.BooleanField(default=False) name = models.CharField(max_length=200) class ContestEntry(TimeStampedModel): name = models.CharField("Track name", max_length = 255) artist = models.CharField("Artist", max_length = 255) url = EmbedVideoField(); description = models.TextField("Description*", blank=True) slug = models.SlugField(max_length=200, unique=True, null=True) contest = models.ForeignKey(Contest, on_delete=models.CASCADE, null=True) and a view: class EntryCreateView(LoginRequiredMixin, CreateView): model = ContestEntry fields = ['name', 'artist', 'url', 'description'] def form_valid(self, form): form.instance.poster = self.request.user return super().form_valid(form) I want to enter the field Contest in my EntryCreateView programmatically with the first entry from the query SELECT id FROM Contests WHERE is_open ORDER BY created desc -
How to add comments functionality to a django web app?
I want to add the functionality of adding comments in the same html page with post details starting from this class based view. I also have left below the model and the html template that I want to use. Please help me The class based view that I want to use as a starting point : class PostDetailView(DetailView): model = Post The model: class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.content The html template: <div id="comments"> <h3>{{ comments.total }}</h3> <ol class="commentlist"> {% for comment in comments %} <li class="depth-1"> <div class="avatar"> <img width="50" height="50" alt="" src="{{ comment.user.profile.image.url }}" class="avatar"> </div> <div class="comment-content"> <div class="comment-info"> <cite>{{ comment.user }}</cite> <div class="comment-meta"> <time datetime="2014-07-12T23:05" class="comment-time">{{ comment.date_added|date:"F d, Y" }}</time> </div> </div> <div class="comment-text"> <p>{{ comment.content }}</p> </div> </div> </li> {% endfor %} </ol> <!-- /commentlist --> <!-- respond --> <div class="respond"> <h3>Leave a Comment</h3> <!-- form --> <form action="" method="POST"> {% csrf_token %} <fieldset> <div class="group"> {{ form|crispy }} <button class="submit full-width" type="submit">Add Comment</button> </div> </fieldset> </form> <!-- /contactForm --> </div> <!-- /respond --> </div> <!-- /comments --> -
Django makemigrations Segmentation fault
I am trying to run a Django rest api in Docker-compose on a raspberry pi 3B with 1gb of RAM. The postgresql database and the nodejs frontend run without any problem. But for the django backend the output of docker-compose up is a segmentation fault: backend | + python3 manage.py makemigrations restapi backend | No changes detected in app 'restapi' backend | scripts/start_server.sh: line 29: 13 Segmentation fault (core dumped) python3 manage.py makemigrations restapi line 29 in start_server.sh refers to: python3 manage.py makemigrations restapi Any ideas where the segfault is coming from or how I could find out what's the problem? Might this be a memory issue? I configured a 8GB swap alongside the 1GB RAM. Would this prevent python to run out of memory? The exact same configuration runs fine on my PC with 8GB RAM so I suppose there isn't a problem with my django models. Edit: if i skip the makemigrations and jump to migrate I also get a segfault: backend | Applying restapi.0001_initial... OK backend | Applying sessions.0001_initial... OK backend | scripts/start_server.sh: line 31: 13 Segmentation fault (core dumped) python3 manage.py migrate