Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateSyntaxError at Could not parse the remainder:
I'm new to Django and trying to get path details of one specific image from the ProductImage table using the place field in the table and display the image.Where place == 'Main Img' Product and ProductImage has one to many relationship. My database has two tables named Product(id, name, price,..) and ProductImage(id, productid, image, place) which contains three images('Main IMG', 'Sub Img 1', 'Sub Img 2') Here is my models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length=200) desc = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) discount = models.DecimalField(max_digits=4, decimal_places=0) def __str__(self): return self.name class ProductImage(models.Model): PLACEHOLDER= ( ('Main Image', 'Main Image'), ('Sub Img 1', 'Sub Img 1'), ('Sub Img 2', 'Sub Img 2'), ) product = models.ForeignKey(Product, related_name='image_set', on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') place = models.CharField(max_length=20, choices=PLACEHOLDER) def __str__(self): return str(self.id) views.py def menu(request): products = Product.objects images = ProductImage.objects context = {'products': products, 'images': images} return render(request, 'store/menu.html', context) Template {% for product in products.all %} <a href="#"> <img src="{{ images.filter(product__id=product.id, place='Main Product Image')[0].image.url }}" class="img-fluid mt-3"> {% if product.discount != 0 %} <span class="bonus">{{ product.discount }}% off</span> {% endif %} </a> settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Media files … -
Hbase login with django
Good morning, I have a question, I am new in apache Hadoop and django. I am creating login in django but i don't know how customing it becouse only know native methods like: "authenticate()" and "login()", now I am using login() but this needs a model user auth instance. I need create a login based in hbase tables. This is my example code user = User.objects.get(username=username) login(request,user) But in the user var recive a instance of mysql model and I need use Hbase Thanks in advance -
Django Form - Create new entries with multiple foreign k
I have searched a lot about this topic here, but i haven't found the right answer. Here is my problem, i want to create a form(not in admin) where the website users can create new entries, and fill the foreign key for my model Market (who has multiple foreignkey to other models). So in this this form the user can create new entries from the models city, provider and service.(i hope i explain it well) What i try to do is to fill 4 models with a single submit for the user. So far i managed to save one foreign key, using instance with and inlineformset_factory, but i want to know what i have to do in order to write the user input in my 4 models. I want to have only one entry for the models that are related as foreign key, that's why i put extra and max_num at 1 and can_delete as false here is my code, hoping you'll be able to help me. Thanks in advance models.py from django.db import models class Market(models.Model): number = models.CharField(max_length=7) title = models.CharField(max_length=200) description = models.CharField(max_length=200) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True) service = models.ForeignKey(Service, on_delete=models.CASCADE, null=True) provider = models.ForeignKey(Provider, on_delete=models.CASCADE, … -
In django are @transaction.atomic auto applied to nested methods also
I have just started learning django and came across this confusion consider the below code @transaction.atomic def first_method() doing stuff calling_method() def calling_method() items = item.objects.filter(item_id__in=[list of items]) for item in items: item.save() Will the above code save item records one by one in db or will it save all the items at once because I have used @transaction.atomic at the first method? If I have to save all the item records at once in db should I use @transaction.atomic in calling_method() as well? -
Django: put all loop result into one bloc json
Django - Json I've tried many time to get all the result of the loop ['results'][0]['analyzedInstructions'][0]['steps'][steps] (multiple results) in only one bloc. But that does not work. Do you have any idea to get all this results and put them together? All others fields works, and the json location is good. try: name = response_title_data['results'][0]['title'] ... steps = "" for step in response_title_data['results'][0]['analyzedInstructions'][0]['steps']: steps += step.step current_post = get_object_or_404(Post, slug=self.slug) create_recipe = self.recipe.create(name=name,source=source,url=url,score=score_brut,steps=steps) current_post.recipe.add(create_recipe) except Exception as e: pass -
Django queryset annotation filters (for max)
I have the following model: class Room(models.Model): # model fields class Table(models.Model): room = models.ForeignKey( Room, [...], related_name='tables' ) class Seat(models.Model): table = models.ForeignKey( Table, [...], related_name='seats' ) timestamp = models.DateTimeField(auto_now_add=True) is_vip = models.BooleanField(default=False) I would like to get the timestamp of the latest seat with a vip on it. Getting the latest seat is easy like this: Room.objects.all().annotate(latest_seat=Max('tables__seats__timestamp')) But how do I filter this on is_vip=True only? -
Django recursive foreign key use template improve sql query
I want improve database sql query Need to change models.... Now 1reply 3 database sql My model Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) reply = models.ForeignKey('self', related_name='reply', on_delete=models.SET_NULL, null=True) content = models.TextField() My template(relpy.html) <li> <label>{{ comment.author }}</label> <p>{{ comment.content }}</p> </li> <li class="gb-padding-left_large"> <form method="post" action="{% url 'post_detail' post.board.pk post.pk %}"> {% csrf_token %} <input type="hidden" required="true" name="comment_id" value="{{ comment.pk }}"/> <input type="text" required="true" name="content" placeholder="reply"/> <input type="submit" placeholder="submit"/> </form> </li> <div class="gb-padding-left_x-large reply"> {% for reply in comment.reply.all %} {% include 'boards/reply.html' with comment=reply %} {% endfor %}</div> -
Django Apache2 VirtualEnv - no response from server
So I am trying to migrate my app to a new production server. I'm not getting a reply from the server Apache server when I access it. The server is on AWS and it's a standard Apache config with just one site enabled: <VirtualHost *:80> Alias /static/ /home/ubuntu/myapp/myapp/myapp/static Alias /media/ /home/ubuntu/myapp/myapp/myapp/media <Directory /home/ubuntu/myapp/myapp/myapp/static> Require all granted </Directory> <Directory /home/ubuntu/myapp/myapp/myapp/media> Require all granted </Directory> <Directory /home/ubuntu/myapp/myapp/myapp> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> WSGIDaemonProcess myapp python-home=/home/ubuntu/myapp/myapp/myapp python-path=/home/ubuntu/myapp:/home/ubuntu/myapp/lib/python3.6/site-packages WSGIProcessGroup myapp WSGIScriptAlias / /home/ubuntu/myapp/myapp/myapp/myapp/wsgi.py ErrorLog /var/log/apache2/myapp_error.log LogLevel warn CustomLog /var/log/apache2/myapp_access.log combined </VirtualHost> I have made sure that all files are owned by the ubuntu user and that www-data has group rights. The wsgi file is the original, but I added a print statement to see the folder it's checking for the application: """ WSGI config for match2 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os, sys print(sys.path) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") application = get_wsgi_application() Eventually, the error log will produce: Timeout when reading response headers from daemon process 'myapp': /home/ubuntu/myapp/myapp/myapp/myapp/wsgi.py I'd appreciate any advice. -
Reading file from other folder in Django
My file structure is: project --support_file --topic_cluster.json recommend.py i am trying to read topic_cluster.json in recommend.py file.My code for the same is with open("project/support_file/topic_clusters.json") as f: topic_clusters=json.load(f) It is giving me FileNotFoundError: [Errno 2] No such file or directory: -
certbot works in command line but fails when running through django call to script
So I have been dealing with this problem for days now and have exhausted every possible thing I can think of. For clarification purposes I am running Machine: Centos 7 WebServer: Django Python Version: 3.6 I have this shell script at /usr/local/bin/activate_https_hostedvoice #!/bin/bash echo "<REMOVE_FOR_SECURITY>" | sudo -S curl -i -XPOST "http://<REMOVED_FOR_SECURITY>/records/""$1""/""$2""" sleep 10 NGINX_CONFIG_FILE=/etc/nginx/guiconf.d/guiserver.conf sed -i "s/]/,'""$1""']/g" /var/lib/guiserver/astgui2/db_pass.py echo "<REMOVE_FOR_SECURITY>" | su -c "/sbin/service guiserver reload" root echo "" >> ${NGINX_CONFIG_FILE} echo "server{" >> ${NGINX_CONFIG_FILE} echo "server_name $1;" >> ${NGINX_CONFIG_FILE} echo "client_max_body_size 4G;" >> ${NGINX_CONFIG_FILE} echo "include guiconf.d/server_params;" >> ${NGINX_CONFIG_FILE} echo "include guiconf.d/static_files;" >> ${NGINX_CONFIG_FILE} echo "include guiconf.d/web_path;" >> ${NGINX_CONFIG_FILE} echo "include guiconf.d/local_path;" >> ${NGINX_CONFIG_FILE} echo "include guiconf.d/ws_path;" >> ${NGINX_CONFIG_FILE} echo "}" >> ${NGINX_CONFIG_FILE} echo "<REMOVE_FOR_SECURITY>" | su -c "systemctl reload nginx" root echo "<REMOVE_FOR_SECURITY>" | su -c "systemctl stop iptables" root echo "<REMOVE_FOR_SECURITY>" | su -c "certbot --nginx -d ""$1"" --agree-tos --email <REMOVED_FOR_SECURITY> -n" root echo "<REMOVE_FOR_SECURITY>" | su -c "systemctl reload nginx" root echo "<REMOVE_FOR_SECURITY>" | su -c "systemctl start iptables" root echo "<REMOVE_FOR_SECURITY>" | su -c "/sbin/service guiserver reload" root echo "<REMOVE_FOR_SECURITY>" | su -c 'echo "0 */12 * * * certbot --nginx renew -n" >> /var/spool/cron/root' root echo "<REMOVE_FOR_SECURITY>" | su -c "rm -f /var/lib/guiserver/bin/https_config" … -
password field is missing in forms django?
I want to replace username with email in django authentication.So when I was going through documentation it says that If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you So First I created a custom user model which extends AbstractUser.In which I made username=None and USERNAME_FIELD='email' class User(AbstractUser): username = None first_name = None last_name = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] Then I created a modelform which uses custom user model.When I render this form in my template, password and confirm password field is missing.I don't know whats going wrong. class UserForm(forms.ModelForm): class Meta: model = get_user_model() fields = ['email'] I thought password and confirm password will be there by default.Am I right? -
How do I plot multiple xy arrays using Chartsjs?
I'm trying to plot to xy arrays using chartsjs x1 = [1,2,3,4,5,6] y1 = [2,4,6,8,10,12] x2 = [4,5,6] y2 = [3,6,9] I can do: var myChart = new Chart(ctx, { type: 'line', data: { datasets: [{ label: 'Scatter Dataset', data: [{ x: 1, y: 2 }, { x: 2, y: 4 }, { x: 3, y: 6 }] { label: 'Scatter Dataset2', data: [{ x: 4, y: 3 }, { x: 5, y: 6 }, { x: 6, y: 9 }] }] }, The problem is that i have a larger x1,y1,x2,y2 array. How do I place a whole array of xy values instead of individual xy values? Instead of data: [{ x: 1, y: 2 }, { x: 2, y: 4 }, { x: 3, y: 6 } I want to be able to do data: [{ x: [1,2,3] y: [2,4,6] }] Do you recommend any other libraries/packages other than chartsjs? -
How the change the appearance of btn btn-outline-success using Django?
I am struggling with button appearance in Django. I implemented a button in this way: <form class="form-inline mt-2 mt-md-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> At this moment, the button has a green border color, a green text and a green hover when the mouse is on it. I really would like to change these properties but maybe I am messing with CSS. Could you help me? Thank you so much -
django ImageField not saving files in proper directory via django rest framework
When post request is sent the images is saved in media/user_None/pic/1602746423.311224_profile.png instead of media/user_{id}/pic/1602746423.311224_profile.png Teacher Model class Teacher(AbstractUser): profile_pic = models.ImageField(verbose_name="Profile Picture",blank=True,null=True,upload_to=file_pic,default='default.png') middle_name = models.CharField(max_length=30, blank=True, null=True) dob = models.DateField(verbose_name='Date Of Birth', null=True) doj = models.DateField(verbose_name='Date Of Join', null=True) mobile_num = models.CharField(verbose_name='Mobile Number',max_length=10,null=True,blank=True) SEX_CHOICE = ( ('m','Male'), ('f','Female'), ('t','Transgender'), ('o','Others') ) sex = models.CharField(max_length=1,choices=SEX_CHOICE,default='m') department = models.ForeignKey('Department',on_delete=models.SET_NULL,null=True) file_pic function for ImageField, to save photos in users folder based on its id def file_pic(instance, filename): return 'user_{0}/pic/{2}_{1}'.format(instance.id, filename, time.time()) Serializer for teacher creation class TeacherCreateSerializer(ModelSerializer): password2 = CharField(write_only=True, style={'input_type':'password'}) class Meta: model = Teacher fields = [ 'username', 'email', 'mobile_num', 'first_name', 'middle_name', 'last_name', 'dob', 'doj', 'sex', 'department', 'profile_pic', 'password', 'password2' ] extra_kwargs = { 'password' : {'write_only':True, 'style':{'input_type':'password'}} } def create(self,validated_data): vd_cpy = validated_data password1 = vd_cpy['password'] password2 = vd_cpy['password2'] vd_cpy.pop('password2') vd_cpy.pop('password') teacher = Teacher(**vd_cpy) if(password1!=password2): raise ValidationError('password doesn\'t match') teacher.set_password(password1) teacher.save() return validated_data def validate_mobile_num(self,value): value = self.initial_data.get('mobile_num',None) if value is None or len(value) == 0: return None if(re.search(r'^((\+?91|0)?){1}[1-9]{1}[0-9]{9}$',value) is None): raise ValidationError('Invalid Mobile Number') return value def validate_email(self,value): if(Teacher.objects.filter(email=value).exists()): raise ValidationError('email already registered') return value APIView for teacher creation class TeacherCreateAPIView(CreateAPIView): queryset = Teacher.objects.all() serializer_class = TeacherCreateSerializer permission_classes = [AllowAny] parser_classes = (JSONParser,FormParser,MultiPartParser) What DRF API explorer shows just … -
Django ImageField is not accessed when in for loop
I'm using telebot to create Telegram bot and Django for model management. When I try to send post to multiple users through a loop I get an error on trying to access ImageField Here is my code def empty_generator(*kwargs): return types.InlineKeyboardMarkup() @bot.message_handler(commands=['test']) def test_send(message): post = Mailing.objects.get(id=79) for i in range(0, 3): print(post.file, len(post.file)) send_generator_with_preview(message.chat.id, post, post.broadcast_language, empty_gener) def send_generator_with_preview(chat_id, post, ln, generator): if (post.file): if post.text: # No photo post bot.send_photo(chat_id, caption=post.text, photo=post.file, reply_markup=generator(post, ln), parse_mode='markdown') else: # No text post bot.send_photo(chat_id, photo=post.file, reply_markup=generator(post, ln), parse_mode='markdown') else: # No Image post bot.send_message(chat_id, text=post.text, reply_markup=generator(post, ln), parse_mode='markdown') Unfortunately, trying to run this code will result in an error: > ERROR - TeleBot: "ApiException occurred, args=('A request to the > Telegram API was unsuccessful. The server returned HTTP 400 Bad > Request. Response > body:\n[b\'{"ok":false,"error_code":400,"description":"Bad Request: > file must be non-empty"}\']',) Traceback (most recent call last): > File > "/Users/number16/Documents/GitHub/urus-master/venv/lib/python3.7/site-packages/telebot/util.py", > line 62, in run > task(*args, **kwargs) File "/Users/number16/Documents/GitHub/urus-master/urus/bot.py", line 1628, > in test_send > send_generator_with_preview(message.chat.id, post, post.broadcast_language, empty_gener) File > "/Users/number16/Documents/GitHub/urus-master/urus/bot.py", line 1691, > in send_generator_with_preview > reply_markup=generator(post, ln), parse_mode='markdown') File "/Users/number16/Documents/GitHub/urus-master/venv/lib/python3.7/site-packages/telebot/__init__.py", > line 700, in send_photo > parse_mode, disable_notification, timeout)) File "/Users/number16/Documents/GitHub/urus-master/venv/lib/python3.7/site-packages/telebot/apihelper.py", > line 315, in send_photo > … -
i'm trying to push my python-django app to heroku, here is the code from the teminal and settings.py :
I get the error in the terminal ( AttributeError: module 'posixpath' has no attribute 'adspath') i tried changing the BASE_DIR file and nothing worked, I fixed the static files and it didn't work either, be patient with my problem please, I have been trying for 3 days to upload this app and this is my final resort. thank you for checking out my question.. This is my terminal after running git push heroku master: git push heroku master Enumerating objects: 6962, done. Counting objects: 100% (6962/6962), done. Delta compression using up to 4 threads Compressing objects: 100% (4022/4022), done. Writing objects: 100% (6962/6962), 15.05 MiB | 189.00 KiB/s, done. Total 6962 (delta 1888), reused 6927 (delta 1865), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.9.0 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.10 remote: Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) remote: Collecting dj-database-url==0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting dj-static==0.0.6 remote: Downloading dj-static-0.0.6.tar.gz (3.4 kB) remote: Collecting Django==3.1.2 remote: Downloading Django-3.1.2-py3-none-any.whl (7.8 MB) remote: Collecting django-bootstrap3==14.1.0 remote: Downloading django_bootstrap3-14.1.0-py3-none-any.whl (23 kB) remote: Collecting gunicorn==20.0.4 … -
String keys to human readable text in django
I am trying to transform various message keys to a human readable text in a template, for example: database_skill => "Database Skill" experience_3_4 => "3 to 4 years of experience" I tried with internationalization but it doesn't seem to be working correctly. A .po file is generated for en-us, I add the "translation" but I can not see it in the template once I use it: msgid "database_skills" msgstr "Database Skills" Template: {% load i18n %} Translated: {% translate "database_skills" %} => this still shows "database_skills" My settings: LOCALE_PATHS = ( os.path.join(BASE_DIR, "app/locale"), ) LANGUAGE_CODE = "en-us" LANGUAGES = ( ('en-us', 'English'), ) Am I doing something wrong? Or should I go for another approach? -
Secure a django form from altered input value
I have the following models (simplified for the question). class Dossier(models.Model): email = models.EmailField(max_length=200, verbose_name="E-mail") creation_date = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=StatusDossier.choices, default=1) uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) def save(sefl, *args, **kwargs): obj_c, creat_c = Candidat.objects.get_or_create( email=self.email, dossier=self, maindossier=obj ) super(Dossier, self).save(*args, **kwargs) class Applicant(models.Model): email = models.EmailField() first_name = models.CharField(max_length=64, blank=True, null=True) last_name = models.CharField(max_length=64, blank=True, null=True) dossier = models.ForeignKey(Dossier, on_delete=models.CASCADE) Every time Dossier is created, a Candidat is automatically created. Nothing fancy. In my workflow, the said applicant then receives an email with a link that brings him to a Form that he has to fill and submit. Here are the form : class CandidatTourForm(models.ModelForm): class Meta: model = Candidat fields = [ "email", "first_name", "last_name", "dossier", ] It's a rather classical form, nothing special about it. But i've been testing my view function (see below) and I noticed that when I do a POST request using postman, if I alter the dossier id provided in the form (hidden field) and replace it with another existing id, the Candidat is of course saved to the Dossier corresponding to the id given in the POST request. Here is the view: def candidat_form_tour(request, dossier_uuid, candidat_id): dossier = get_object_or_404(Dossier, uuid=dossier_uuid) candidat = … -
How can create, list, and destroy be performed in one view at a time in django?
I made a like model to implement the like function and made a corresponding view so that it would be good to send a post request. By the way, I am going to implement this one view to be unlike if I receive a delete request at once. So I will first use get method to get one like model and then map the pk of that like model to url. But when I send a delete request to the view, the following error appears. Traceback (most recent call last): File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "D:\school\대회 및 프로젝트\CoCo\feed\views.py", line 138, in destroy super().destroy(request, *args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\mixins.py", line 90, in destroy instance = self.get_object() File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\generics.py", line 88, in get_object … -
ValueError at /profiles/user-profile/ Field 'id' expected a number but got 'handsome'
Well I am trying to add or remove user from follower list of particular user and user to toggle and profile of user if correct but it showing me this error when i hit on a follow button . How can i fix it ? models.py class ProfileManager(models.Manager): def toggle_follow(self, request_user, username_to_toggle): profile_ = UserProfile.objects.get(user__username__iexact=request_user) user = request_user is_following = False if username_to_toggle in profile_.follower.all(): profile_.follower.remove(username_to_toggle) else: profile_.follower.add(username_to_toggle) is_following = True return profile_, is_following class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() viewspy class UserProfileFollowToggle(View): def post(self, request, *args, **kwargs): username_to_toggle = request.POST.get("username") profile_, is_following = UserProfile.objects.toggle_follow(request.user, username_to_toggle) return redirect(f'/profiles/{username_to_toggle}') if more detial is require than tell me i will update my question with that information. -
python: run few lines of code independently and return the value
In my Django project, I am having some user defined code logic which needs to be implemented averageValue=0; for n in range (0,7) averageValue=averageValue+price[1+n]*volume[1+n]; end score=price[1]*volume[1]/averageValue; return score; For this code i will be passing the price[] (array) and volume[] (array) Currently this code is stored in database I can get the code in django using customlogic = CustomLogic.objects.get(id=1)['code'] I want the logic code to run entirely different env, without having access to any other variables in the main code ..main code .. populate price[] (array)` and `volume[] (array)` .. customlogic = CustomLogic.objects.get(id=1)['code'] # get score from the customlogic by passing price[] and volume[] .. score = customlogic (pass) price[] volume[] and then i can save the store in the db -
Running collectstatic command from Dockerfile
My goal is to run collectstatic command inside Dockerfile, but when trying to build the image, I run into KeyError messages coming from settings.py file on lines where environmental variables are used, for example: os.environ['CELERY_BROKER'] This is apparently because the container is not yet built, so Docker does not know anything about the environment variables. Is there any command to import all the variables to Docker? Or maybe it's a bad idea to run the collectstatic command inside Dockerfile and it should be run inside docker-compose file ? Or maybe as part of a CI/CD task ? My Dockerfile looks like this: COPY . /app/ WORKDIR /app RUN . .env RUN python manage.py collectstatic --noinput RUN ls -la -
How to match objects based on selected manytomany in Django orm
Im trying to get objects based on selected/added items in a ManyToMany field. My models: class Location(models.Model): name = models.CharField(max_length=45) class BenefitLocation(models.Model): benefit = models.ForeignKey(Benefit) location = models.ForeignKey(Location) class Benefit(models.Model): locations = models.ManyToManyField(Location, through='BenefitLocation') Here is what Im trying to do in the orm: selected_locations = Location.objects.filter(id__in[1,2]) #Getting IDs from api request matching_benefits = Benefit.objects.filter(locations=selected_locations) In matching_benefits, I only want those with exactly these selected locations. When I try my code, I get this error: django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row') How can I get the matching_benefits? -
Multivendor Django Ecommerce can it possible?
I'm trying to build a multivendor ecommerce web application like Amazon for example. For this project I used a python with Django, but now I don't know how to create the same page for each supplier, with the ability to each enter their own products and data. I am looking for a tutorial or documentation on this. Can anyone help me ?. Thank you! -
Why is Django admin giving me TemplateDoesNotExist Error
Using Django==3.1, when I try and go to the admin pages, I'm getting the error raise TemplateDoesNotExist(template_name, chain=chain) admin/apidocs_index.html I never used to get this happening. my urls: urlpatterns = [ path('copo/', include('web.apps.web_copo.urls', namespace='copo')), path('admin/', admin.site.urls), path('rest/', include('web.apps.web_copo.rest_urls', namespace='rest')), path('api/', include('api.urls', namespace='api')), path('accounts/', include('allauth.urls')), path('accounts/profile/', views.index), path('', TemplateView.as_view(template_name="index.html"), name='index') ] and template settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # insert your TEMPLATE_DIRS here os.path.join(BASE_DIR, 'web', 'landing'), os.path.join(BASE_DIR, 'web', 'apps', 'web_copo', 'templates', 'copo'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.csrf', 'django.template.context_processors.request', 'django.template.context_processors.static', # processor for base page status template tags "web.apps.web_copo.context_processors.get_status", "web.apps.web_copo.context_processors.add_partial_submissions_to_context", 'django.contrib.auth.context_processors.auth', ], 'debug': True, }, }, ] I don't have any more details to add at this time