Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need Good Python Courses and Study material
I am quite new to Programming, with past few experience in JAVA,Now looking forward to learn Python, Please suggest some really good and interactive courses and Study Materials that I could follow along.The aim is to go from Scratch to be able to tackle some Data structures problems. -
Can't handle exceptions in requests
For some reason I can't handle exceptions using requests library at all. Here's my code: import requests p = open('file.txt', 'r') ls = p.readlines() while True: c = 0 ps = {'http': ls[c].replace('\n', '')} r = requests.get('targeturl', proxies=ps, timeout = 10) if r: try: print('Success.') w = open('savefile.txt', 'w') w.write(ls[c]) c += 1 except Exception: print("Failure.") continue # OR except: print('Failure.') continue The purpose of my code is to check the proxy list on the targeturl, and save the working ones into a file. Those except statements should just print 'Failure.' and continue, but they don't. I always get the same errors every time. I even tried handling literally every error I see, still get the same problem. except requests.exceptions.HTTPError as errh: print ("Http Error:",errh) except requests.exceptions.ConnectionError as errc: print ("Error Connecting:",errc) except requests.exceptions.Timeout as errt: print ("Timeout Error:",errt) except requests.exceptions.RequestException as err: print ("OOps: Something Else",err) Here's what I always get: Traceback (most recent call last): File "C:\Users\mon-pc\AppData\Roaming\Python\Python36\site-packages\requests\packages\urllib3\connection.py", line 138, in _new_conn (self.host, self.port), self.timeout, **extra_kw) File "C:\Users\mon-pc\AppData\Roaming\Python\Python36\site-packages\requests\packages\urllib3\util\connection.py", line 98, in create_connection raise err File "C:\Users\mon-pc\AppData\Roaming\Python\Python36\site-packages\requests\packages\urllib3\util\connection.py", line 88, in create_connection sock.connect(sa) socket.timeout: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File … -
I want to parse and upload a large csv file into a msql database, but its taking forever. Python/Django
def process_data(self): f = io.TextIOWrapper(self.cleaned_data['data_file'].file, encoding='utf-8-sig') reader = csv.DictReader(f) for row in reader: Csv.objects.create(starttime=datetime.strptime(row["startTime"], '%Y-%m-%d %H:%M:%S'), incidents_id=(row['id']), type=(row['type']), subtype=(row['subtype']), reportdescription=(row['reportDescription']), street=(row['street']), reportby=(row['reportBy']), longitude=Decimal(row['longitude']), latitude=Decimal(row['Latitude']), endtime=datetime.strptime(row["endTime"], '%Y-%m-%d %H:%M:%S'), dataowner_id=1) -
Django Webpack Loader setting does not render images
I am using Django webpack loader to render VueJs files. I have two similar applications and I can view the images in one application but other does not work. This is how I configure my Vue Webpack: const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config.module.rules.delete('eslint'); config.optimization .splitChunks(false) config.module .rule('vue') .use('vue-loader') .loader('vue-loader') .tap(options => { options.transformAssetUrls = { img: 'src', image: 'xlink:href', 'b-img': 'src', 'b-img-lazy': ['src', 'blank-src'], 'b-card': 'img-src', 'b-card-img': 'src', 'b-card-img-lazy': ['src', 'blank-src'], 'b-carousel-slide': 'img-src', 'b-embed': 'src' } return options }) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}]) config.resolve.alias .set('__STATIC__', 'static') config.devServer .public('http://0.0.0.0:8080') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({"Access-Control-Allow-Origin": ["\*"]}) } }; These are my Django settings: WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': DEBUG, 'BUNDLE_DIR_NAME': '/bundles/', # must end with slash 'STATS_FILE': os.path.join(FRONTEND_DIR, 'webpack-stats.json'), } } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") and urls.py: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have been struggling for two days. I can get the url as text in the template, meanwhile images are not rendered as image. Anyone has a clue ? Thanks -
Get all users which passed the exam
I need help in django queries. I have ExamResult model which keep results of exam. How get all users which passed the exam and are in the same study group. ExamResult model class ExamResult(Model): exam = ForeignKey(Exam, blank=False, null=False, on_delete=CASCADE) score = IntegerField() user = ForeignKey('Accounts.UserAccount', blank=False, null=False, on_delete=CASCADE, ) exam_date = DateTimeField(auto_now_add=True, blank=False, null=False) StudyGroup model class StudyGroup(models.Model): group_name = models.CharField(max_length=10, blank=False, null=False) -
Django - One to Many Single Query on Same Table - Get Most Recent and Oldest on Group By
Suppose I have the following: from django.db import models class Book(models.Model): name = models.CharField(max_length=300) price = models.DecimalField(max_digits=10, decimal_places=2) class Customer(models.Model): name = models.CharField(max_length=300) class Sale(models.Model): date = # Some date or insertion time stamp payment_method = models.CharField(max_length=300) book = models.ForeignKey(Book, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) ---------- I've searched through many forums and the Django docs but I'm still a bit confused. If I want to have a query for all books, but also include the name of the first and last customer that purchased a said book with said payment method, how would I accomplish this? Where the SQL equivalent of the joins would be: SELECT a.name as book_name, a.price as book_price -- More selects on individual customer names or sale payment methods FROM Book a LEFT JOIN ( SELECT first_sale.* FROM Sale first_sale WHERE date = ( SELECT MIN(date) FROM Sale c WHERE b.id = c.id ) ) b ON b.book = a.name -- Some kind of join LEFT JOIN ( SELECT last_sale.* FROM Sale last_sale WHERE date = ( SELECT MAX(date) FROM Sale c WHERE b.id = c.id ) ) c ON c.book = a.name -- Some kind of join LEFT JOIN Customer d ON d.id = b.customer_id … -
Django djoser user registration with email confirmation
I'm using Django and djoser as backend for a mobile app. When I make following POST request: curl -X POST http://127.0.0.1:8000/auth/users/ --data 'username=myusername&email=myemail&password=mypwd' I receive an email to myemail with the activation link with the proper uid and token. Then I try to activate the user by doing: curl -X POST http://127.0.0.1/auth/users/activation/ --data 'uid=myuid&token=mytoken' After this I get a 404 NOT FOUND response. Djoser documentation says the activation endpoint is /users/activation/. My urls.py is as follows: from django.contrib import admin from django.urls import include, path, re_path urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('api.urls')), re_path(r'^auth/', include('djoser.urls')), ] Does anybody know what I'm doing wrong? Thank you so much for your support! -
How can i dynamically update the graph using Django-Ajax-Snowflake?
I'm trying to update the graph dynamically which gets values from the table and whenever the user changes/enters any value it should reflect in the graph automatically without having a refresh button. How to do that using Django-ajax-snowflake any suggestions to do that, definitely not in Dash. Here is the code for my table: <table id="" class=""> <thead> <tr> <th>Bump!</th> <th>C1</th> <th>C2</th> <th>C3</th> <th>NUMERATOR</th> <th>DENOMINATOR</th> </tr> </thead> <tbody> {% for x in measures %} <tr> <th> <input type="checkbox" id="" class=""> </th> <td> {{x.C1}} </td> <td>{{x.C2}}</td> <td>{{x.C3}}</td> <td><input class="" type="text" value="{{x.NUMERATOR}}"></td> <td><input class="" type="text" value="{{x.DENOMINATOR}}"></td> </tr> {%endfor%} </tbody> </table> -
How do I add link to another page [Django 3.0]? Reverse not found
I'm trying to add link (to blogDetails.html) to anchor on the main page and cannot do it (without Django it takes approximately 1,2 sec). index.html <a href="{% url 'blogDetails' %}">O blogu</a> urls.py path('blogDetails/', views.BlogDetailsPageView.as_view(), name='blogDetails'), views.py class BlogDetailsPageView(TemplateView): template_name = 'blog/blogDetails.html' Error I get: Reverse for 'blogDetails' not found. 'blogDetails' is not a valid view function or pattern name. What on earth is going on here? All help appreciated. -
Increment a variable within django template tags
I'm creating a registration form, where the user can pick multiple shirt sizes. There is a shirt model, in which one of the fields is a "quantity" of the quantity of the shirt size that the user wishes to purchase with their registration. If the user does not select any extra shirts, I want to print "No extra shirts." {% with totalshirts=0 %} {% for s in shirts %} {% if s.quantity > 0 %} <div class="flex"> <p class="confirm-text" style="width: 210px">{{ s.size.name }}:</p> <p class="confirm-text"><span class="txt-grey">{{ s.quantity }} shirt{{ s.quantity|pluralize }} | {{ event.extra_shirts_price | currency }}</span></p> </div> {% endif %} {{ totalshirts|add:s.quantity }} {% endfor %} {% if totalshirts == 0 %} <p class="footer-text">No extra shirts.</p> {% endif %} {% endwith %} I tried to increment the quantity each time the for loop is run, but it returns 0 unless the user selects the last shirt size (XXXL). The variable seems to default to 0 every time the loop is run. Here is an example of the output of this program Extra Shirts 0 Youth Large: 1 shirt | $10.00 1 0 Adult Medium: 1 shirt | $10.00 1 Adult Large: 1 shirt | $10.00 1 0 0 0 … -
Guardar multiples imágenes en django 2.2
no puedo guardar todas las imágenes que agrego en el formulario este es el código de las views Views models y este es el error que aparece enter image description here -
Django adding new attribute to WSGIRequest
Hey im kinda new to Django and the whole Views/Request process. So I noticed i got the auth_user inside the request object due to the User middleware I had inside the settings file, and anywhere i have the request, i can call the user object with request.user I kinda have a similar modal/object that is pretty important and I saw how to create a basic middleware but I'm not for sure how to replicate similar functionality where I'd be able to access that specific object inside the request like "request.object" -
checking the display of publications (tests)
in short: test lines: [..] print(self.post.created_at) # 2019-12-10 19:10:28.362152+00:00 print(timezone.now()) # 2019-12-10 19:10:28.517711+00:00 resp = self.client.get(reverse_lazy('posts:post_list')) self.assertIn(self.post, resp.context['posts']) assertIn is TRUE if in my views: queryset = Post.objects.filter() assertIn is FALSE if in my views: queryset = Post.objects.filter(created_at__lte=timezone.now()) # print(resp.context['posts']) shows nothing in tests In production all works well. If you have any idea why I get False, please let me know! Thanks! -
Django extension graph_models doesn't generate the characters
I ran a Django app on a Docker container, then ssh into it and pip install pydotplus and apk add graphviz, then I ran ./manage.py graph_models -a -g -o my_project_visualized.png. It generated a file with model and relationship. But all the characters render as squares, as if they are unicode or something. All my models are English, so should be within ascii range. -
BASH: Launching a server in the background
I have a Django AWS server that I need to keep running over the weekend for it to be graded. I typically start it from an SSH using PuTTY with: python manage.py runserver 0.0.0.0:8000 I was originally thinking of making a bash script to do the task of starting the server, monitoring it, and restarting it when needed using the but was told it wasn't going to work. Why?. 1) Start the server using python manage.py runserver 0.0.0.0:8000 & to send it to the background 2) After <some integer length 'x'> minutes of sleeping, check if the server isn't up using ss -tulw and grep the result for the port the server should be running on. 3) Based on the result from step (2), we either need to sleep for 'x' minutes again, or restart the server (and possibly fully-stop anything left running beforehand). Originally, I thought it was a pretty decent idea, as we can't always be monitoring the server. My partner looked at me in disbelief as if I said something silly, and I can't figure out why. -
why does my link to logout not work in my Django app?
So I'm trying to do a logout link in my Django app. I've set a view that logs out the user and then redirects him to a template paginaPrincinal.html that has two buttons for login and register. The problem is that for some reason the link href that I'm creating in my index.html doesn't appear. my views.py def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect('index') else: form = AuthenticationForm() return render(request, 'registration/login.html', {'form': form}) def logout_view(request): logout(request) return redirect('paginaPrincipal') my urls.py path('principal/', views.intro, name='pagina_principal'), path('registro/', views.registro_usuario, name='registro_usuario'), path('login/', views.login_view, name="login"), path('logout/', views.logout_view, name="logout"), path('',views.index, name ='index'), index.html {% block contenido %} <div> <ul> {% if user.is_authenticated %} <li>Hola, {{user.username}}</li> <li><a href="{% url 'logout' %}"></a></li> {% endif %} </ul> </div> {% endblock %} The error that appears if I inspect the code and try to go to the Href is this: NoReverseMatch at /myapp2/logout/ Reverse for 'paginaPrincipal' not found. 'paginaPrincipal' is not a valid view function or pattern name. -
Verify if exists records in database with Django
My english is bad. Hello everyone, i trying verify if exists records in Database. If exists then not insert. If not exists insert. The problem is that's inserted when exists in DB. Can't insert if exists but is inserted. :( How to fix it? My code is: class Follow(models.Model): followed = models.CharField(max_length=100) following = models.CharField(max_length=100) def __str__(self): return self.followed def verify(self, request, gender): select_me = User.select_me(self, request) select_random = User.select_random(self, request, gender) try: verify = Follow.objects.filter( followed=select_me.twid, following=select_random.twid).exists() if verify: return False else: return True except: return False def follow(self, request, gender): select_me = User.select_me(self, request) select_random = User.select_random(self, request, gender) timer = utils.strtotime('+' + str(configs.FOLLOW_TIME_PREMIUM) + ' minutes') if select_me.premium > 0 else utils.strtotime('+' + str(configs.FOLLOW_TIME_FREE) + ' minutes') if self.verify(request, gender): register = Follow(followed=select_me.twid, following=select_random.twid) register.save() select_me.follow_count += 1 select_me.follow_time = timer select_me.follow_total += 1 select_me.save() return True else: return False -
Django- Cleaning data for a many-to-many field within ModelForm
I'm building an API that will require the cleaning of input data into a modelform m2m field before creating the model instance. The data will come in as a string of names, I will need to clean the data and add link the m2m relationship manually. What is the proper way to link these relationships within the manytomany field during the clean Def. Do I simply append each into the field itself? Below is my working "clean" def: def clean_sourcingbroker(self): broker = self.cleaned_data['broker'] cleanlist = [] names = [] for name in broker.replace(', ', ',').split(' '): name = name.split(',') last_name = name[0] first_name = name[1] names.append((last_name, first_name)) for name in names: brokerobj = Broker.objects.get(lastname=name[0], firstname=name[1]) cleanlist.append(brokerobj) return cleanlist -
Django admin dashboard CSS is missing
I just deployed my application to DigitalOcean. Everything works very well, excep admin panel's styling although I've used nginx. Here are my codes: settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static_root") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] nginx configuration: server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static_root/ { root /home/my_username/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/my_username/myproject/myproject.sock; } } -
Should I have methods that don't return a queryset on a models.QuerySet children?
Right now at work I have a situation like this where I'm trying to find the cleanest way out of it: FooQuerySet(models.QuerySet): def active_items(self, items): new_items = self._do_something_with_items(items) return self.filter(active__in=items) def _do_something_with_items(items): """ some kind of calculation """ The question is, should the method _do_something_with_items leave inside the QuerySet children given that it does not return a queryset but rather does some data transformation, or is it ok to leave it there as it's next to the place that calls it? -
How can I make a log to the db table of errors, all Django operations that have been failed
I am pretty new in Django , and I try to make a log table which contain all the bad operations like : UPDATE,DELETE,CREATE and the reason it has been failed , for example : unique field is already exist. I tried to do it with Signals, pre_post but when an error occur,it even doesn't get into my create() function on my serializer . any ideas ? Thank you! -
Method return TypeError for 2 positional argument instead of 1 that was given
My model manager for Django defines a function that gets or creates new billing profile for either existing user or a guest user depending if the user is authenticated or not. The function takes in only one parameter, but in using it in the view, I'm presented with TypeError that says: TypeError at /cart/checkout new_or_get() takes 1 positional argument but 2 were given For better understanding here is the source source code: Urls.py from django.urls import path from . import views app_name = 'cart' urlpatterns = [ path('checkout', views.checkout_home, name='checkout') ] Model This is before the views because this were I define the function new_or_get() in the class BillingProfileManager() from django.db import models from django.conf import settings from django.db.models.signals import post_save from accounts.models import Guest User = settings.AUTH_USER_MODEL class BillingProfileManager(models.Manager): def new_or_get(request): user = request.user guest_email_id = request.session.get('guest_email_id') obj = None created = False # Logged in user checkout. Remembers payment if user.is_authenticated: obj,created = self.model.get_or_create(user=user, email=user.email) # Guest user checkout. autoreloads payment elif guest_email_id is not None: guest_obj = Guest guest_email_obj = guest_obj.objects.get(id=guest_email_id) obj,created = self.model.get_or_create(email=guest_email_obj.email) created = True else: pass return obj, created class BillingProfile(models.Model): user = models.OneToOneField(User, unique=True, null=True, blank=True, on_delete=models.DO_NOTHING) email = models.EmailField() active = models.BooleanField(default=True) … -
Django File object and S3
So I have added s3 support to one of my Django projects. (storages and boto3) I have a model that has a file field with zip-archive with images in it. At some point I need to access this zip-archive and parse it to create instances of another model with those images from archive. It looks something like this: I access archive data with zipfile Get image from it Put this image to django File object Add this file object to model field Save model I works perfectly fine without s3, however with it I get UnsupportedOperation: seek error. My guess is that boto3/storages does not support uploading files to s3 from memory files. Is it the case? If so, how to fix id/ avoid this in this kind of situation? -
How to store postgresql database in django - project folder?
Where is postgreSQL database saved in a django folder (that which has manage.py)? If not, I presume it must be stored in postgres folder of root directory. Then, how to transfer this file to those systems having no postgres installed, so that when they "run server", they can see seamlessly all the data/app? Can we ask DJANGO to create the databse file in its project folder itself and does this help in such transfers ? Thanks. -
After deploying Django app on AWS elastic beanstalk it shows default page but in local system it works fine
I am deploying Django application to AWS beanstalk , this application works fin in local environemnet but after deploying its shows default page of Django. I tried manually putting urls but it is not working too.