Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MySql: will it deadlock on to many insert - Django?
I wanna migrate from sqlite3 to MySQL in Django. Now I have been working in Oracle, MS Server and I know that I can make Exception to try over and over again until it is done... However this is insert in a same table where the data must be INSERTED right away because users will not be happy for waiting their turn on INSERT on the same table. So I was wondering, will the deadlock happen on table if to many users make insert in same time and what should I do to bypass that, so that users don't sense it? -
Unable to run "heroku login" on Mac
I installed Heroku CLI and ran heroku login command. I entered my credentials and this error came up : ▸ Are you behind a proxy? ▸ https://devcenter.heroku.com/articles/using-the-cli#using-an-http-proxy Then I ran these commands : export HTTP_PROXY=http://proxy.server.com:portnumber export HTTPS_PROXY=https://proxy.server.com:portnumber Then this error came-up : ▸ Post https://api.heroku.com/login: http: error connecting to proxy https://proxy.server.com:portnumber: dial tcp: lookup tcp/portnumber: nodename nor servname provided, or not known Searched all over google but was not able to find anything helpful. I am new to this. Please help. -
Scrapy - ItemPipeline does not enter Process Items
I'm playing around with Scrapy, and trying to pass items generated by Spiders to an ItemPipe. THe issue is, while the pipe is entered, the actual process_items method is never called. That despite having debugged the spider and seeing that it's correctly yielding Quote items. To summarise, when I debug quotes_spider.py I can see the 'item' object I return is of type Quote, with author/quote having expected values. Similarly, the pipe is loaded correctly and the json file is created, I simply never enter the process_items method or write to such file. Any advice? quotes_spider.py import scrapy from scrapy.loader import ItemLoader from tutorial.item_loaders import QuoteLoader from tutorial.items import Quote class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/', ] def parse(self, response): for quote in response.xpath('//div[contains(@class, "quote")]'): l = QuoteLoader(item=Quote(), response=response) content = quote.xpath('./span[contains(@itemprop, "text")]/text()').extract_first() l.add_value('quote', content) author = quote.xpath('./span/small[contains(@itemprop, "author")]/text()').extract_first() l.add_value('author', author) item = l.load_item() yield item Items.py # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class TutorialItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass class Quote(scrapy.Item): quote = scrapy.Field() author = scrapy.Field() item_loaders.py from scrapy.loader … -
Running a custom python script directly from the Django Admin webpage
I have a python script written that takes an input from one model, queries it, and appends the various results from the query to another model through a ForeignKey relationship. It works great from the python shell, but I was wondering if there is a way to run it from the admin webpage so that every time a new object for the first model is submitted, it runs the script and updates the database automatically for the other model. I'm using the Django admin interface as part of development for staff to do data entry since I've found it's a very flexible interface. The script is written specifically for this app, so it is on the app's folder. -
Whic server to save uploaded file?
I have a website in django and my website is for upload image I want to save uploaded file in a other servers(this servers built for this kind of work)and pay then money to save my user uploaded files(images) I want address of this server to go there i pay them and buy i place Note : file should uploaded by user and thenmy app automatic upload them i this server! Note : my uploaded file is too heavy and are more than 1000 image per a day .beacuse of that i can't upload in my host Tnx all 💛 -
Is Django is an appropriate tool for what I'm trying to do?
I have experience using HTML/CSS/Javascript and Python separately, but I'm completely lost on how to use both together (if that's even a thing). I have a Python file that can take input, calculate a value and return it. I thought my final result would be a webpage coded using HTML/CSS, that took a user input, inserted it somehow into that Python file and displayed the output. When I began reading about using Python in webpages, the most popular recommendation seemed to use the framework Django. While going through the tutorial however, Django seemed possibly overkill for what I was trying to do. Is using Django the best way to take user inputs, run Python on them, and display the output to the user? -
ReactorNotRestartable - Twisted and scrapy
Before you link me to other answers related to this, note that I've read them and am still a bit confused. Alrighty, here we go. So I am creating a webapp in Django. I am importing the newest scrapy library to crawl a website. I am not using celery (I know very little about it, but saw it in other topics related to this). One of the url's of our website, /crawl/, is meant to start the crawler running. It's the only url in our site that requires scrapy to be used. Here is the function which is called when the url is visited: def crawl(request): configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'}) runner = CrawlerRunner() d = runner.crawl(ReviewSpider) d.addBoth(lambda _: reactor.stop()) reactor.run() # the script will block here until the crawling is finished return render(request, 'index.html') You'll notice that this is an adaptation of the scrapy tutorial on their website. The first time this url is visited when the server starts running, everything works as intended. The second time and further, a ReactorNotRestartable exception is thrown. I understand that this exception happens when a reactor which has already been stopped is issued a command to start again, which is not possible. Looking at … -
django template - Create a variable by obtaining from context and then append to that evaluate again
Currently I am trying to do something like this which fails {{ {{patient.patient_name}}_date }} Basically my context has a variable called Jordan_date. The name Jordan is the output of {{patient.patient_name}} and I simply want to append to that. So my question is how can I create a evaluation variable dynamically ? I was not sure how to phrase this question so I apologize in advance if the title is weird. -
How to get_available_languages in views.py
I am trying to get in my views.py a list of all the languages I have available. This is easily done in a template through the tag {% get_available_languages as LANGUAGES %} (docs here), but I do not find its equivalent for the views. Is there any simple way to get it? -
Images not loading Django website
Images on my django website are not loading for some reason This is my models.py thumbnail = models.ImageField(upload_to='images/',blank=True) This is my settings.py lines STATIC_URL = '/static/' MEDIA_URL = '/media/' if DEBUG: STATIC_ROOT = os.path.join(BASE_DIR, 'static/static-only') MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/static'), ) This is my views.py class BlogIndex(generic.ListView): queryset = models.Entry.objects.published() template_name = "index.html" paginate_by = 5 In url.py if settings.DEBUG: urlpatterns +=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) In index.html i did this <img class="img-rounded" src = "{{object.thumbnail.url}}"/> The Images are getting saved in the static/media/images directory But the images are not loading in the web page... When i try to right-click and view the image It shows this error SCREEN SHOT Other objects are working perfectly.. Only the images aren't loading -
After registration page the user needs to fill out advice
I'm attempting to add a page after registration which the users needs to fill out, in this case a profile forms. Im currently using django AllAuth which works great and i can add i redirect page after email confirmation using the below settings: ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = What would be the best way to do this, create a page which does not include the standard navbar and just one that doesn't include any links to the users profile for example, so they have no choice but fill out the page? however if the person signs out during the process and they then re-login they will not be redirected to this page, as they have already confirmed their email. Sorry if this very unclear but i have a real lack of webdev. -
Can i pass information between Django and HTML in same request for user?
I am creating certain model's object picker which is activated when user sends a post request via HTML forms. More specifically once user clicks certain submit button and post request is sent to the website, It then returns variable which is then used by javascript to open a status window. Here is all the code associated with these actions: HTML <form id="item_selection1" action="{% url 'Home:AccountPage' %}" method="post"> {% csrf_token %} <input class="sendtrade" name="sendtrade1" type="submit" value="Send Offer"> </form> Python - views.py (3 dots represent all unassociated code) ... prepareTrade1 = "false" ... if request.POST.get('sendtrade1'): prepareTrade1 = "true" ... return render(request, 'Home/name.html', {"...": "...", 'prepareTrade1': prepareTrade1}) Javascript in HTML if ( "{{ prepareTrade1 }}" == "true" ) { $(".process_overlay").css("display", "block") } Shortly, when user clicks the submit button box appears, What i'm trying to do, Is to display status of object query. So for example, If i received ObjectDoesNotExist error from test.py which belongs in the same directory as views.py, How could i direct that information to HTML/Javascript user is receiving? If creation of absolute new request is required, Then still, How could i do that? -
Error introducing simple middleware into app - object() takes no parameters
I am reading about middleware and decided to try this out. The middleware is located inside a file called middleware.py inside an app called mainApp.I introduced the following into my middleware in the settings (last line) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "mainApp.middleware.UserTimezoneMiddleware", #---->added it here ] This is the code that I have so far in mainApp.middleware class UserTimezoneMiddleware(object): """ Middleware to check user timezone. """ def process_request(self, request): user_time_zone = request.session.get('user_time_zone', None) try: if user_time_zone is None: ip = get_client_ip(request) freegeoip_response = requests.get('http://freegeoip.net/json/{0}'.format(ip)) freegeoip_response_json = freegeoip_response.json() user_time_zone = freegeoip_response_json['time_zone'] if user_time_zone: request.session['user_time_zone'] = user_time_zone timezone.activate(pytz.timezone(user_time_zone)) except: pass return None However when I try to run it I get the error File "/Users/admin/Development/ProjectName/lib/python2.7/site-packages/django/core/handlers/base.py", line 82, in load_middleware mw_instance = middleware(handler) TypeError: object() takes no parameters Any suggestions on what I might be doing wrong or how I can fix this issue ? -
Django OAuth Toolkit with Multiple Grants
I'm using Django OAuth Toolkit and I would like to register applications with multiple grants. Some applications may have just one type of grant, others may have more. The official documentation: http://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html#multiple-grants recommends: class MyApplication(AbstractApplication): def allows_grant_type(self, *grant_types): # Assume, for this example, that self.authorization_grant_type is set to self.GRANT_AUTHORIZATION_CODE return bool( set(self.authorization_grant_type, self.GRANT_CLIENT_CREDENTIALS) & grant_types ) but I get an error saying that "TypeError: set expected at most 1 arguments, got 2" Also as I understand this doesn't modify the model in the db. This would return if the intersection of the sets is empty or not. So won't this make (if it works) the GRANT_CLIENT_CREDENTIALS available to all applications? -
Difference between date time field to check if its more or less than X minutes
I have a ticket model. I need to list out the tickets that are from a specific show, also which has been either bought or the time difference between now and booked_at is less than 5 minutes. class Ticket(models.Model): show = models.ForeignKey(Show) seat = models.ForeignKey(Seat) user = models.ForeignKey(User) booked_at = models.DateTimeField(default=timezone.now) bought = models.BooleanField(default=False) unavailable = Ticket.objects.filter(show=show).filter(Q(bought=True) | Q(booked_at = ????)) How can I query for the difference between now and the booked_at field to check if its less/more than X minute? -
Python/Django: __dict__ attribute error message when adding custom fields to UserCreationForm
This error occurs because I have tried to add custom fields to UserCreationForm. I have now made my two custom fields—cristin and rolle—but when I press the signup button, I get the following error message: AttributeError at /accounts/signup/ – 'tuple' object has no attribute '__dict__'. (However, the new user is actually registered and is visible in the admin panel). In my models.py file, I have: ... class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Userextended(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) cristin = models.IntegerField() rolle = models.CharField(max_length=100) ... In my forms.py file, I have: ... class UserCreateForm(UserCreationForm): cristin = forms.IntegerField(required=False) rolle = forms.CharField(max_length=100,required=True) class Meta(): fields = ('username','first_name','last_name','email','password1','password2') model = User def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = 'Email Adress' self.fields['first_name'].label = 'First name' self.fields['last_name'].label = 'Last name' self.fields['cristin'].label = 'Cristin ID' self.fields['rolle'].label = 'Role' def save(self, commit=True): if not commit: raise NotImplementedError("Can't create User and Userextended without database save") user = super(UserCreateForm, self).save(commit=True) user_profile = Userextended(user=user,cristin=self.cleaned_data['cristin'],rolle=self.cleaned_data['rolle']) user_profile.save() return user, user_profile ... What am I doing wrong and where should I place the __dict__ that the error message is asking for? -
Custom column in Django users profile
I want to add custom column in Django admin, on Users (/auth/user/) section. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField() def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() And in admin.py I have this code: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Custom fields' class CustomUser(UserAdmin): inlines = (ProfileInline, ) list_diplsay = ('birthday') def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUser, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, CustomUser) I've read here that list_display should do all the work, but in my case it doesn't work. I don't see any changes in my admin panel since I've added that line. Where is the problem? Thanks! -
How can I use the Default File Storage(S3) to upload files with Django FormTools form wizard?
When uploading files, django-formtools Form Wizard, needs a place to temporarily store the until the user has completed all steps in the wizard. The FormTools documentation shows an example of how to upload a file to a local folder on your server. The file_storage setting is required to upload files. from django.core.files.storage import FileSystemStorage class CustomWizardView(WizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos')) We use Heroku and don't have access to local storage when uploading a file. We use django-storages and S3 to store all our files. I want to use django-storages to manage the upload process. How can I just modify this view so that we use the default storage system to upload this file to a temporary location on S3? -
Is there a way to make a django service communicate with spring service?
So I have been assigned to do a task to bring a new functionality to a web application but the thing is, the current application is written in Spring and I'm not proficient in it. So my plan is to write a separate service for that functionality in django and just call it whenever it is needed. Is this possible? and how? -
Heroku ImportError: froala_editor module not found
I am hosting a Django blog on Heroku. Everything was working fine until I added Froala Editor for editing and creating posts. For this purpose I installed django-froala-editor==2.6.2 module. Now I can't push it back to Heroku. It throws the error: ImportError: No module named froala_editor. The module is listed in requirements.txt. I also tried installing it manually on heroku run command line and it is successfully installed. But at the very next moment I try to import the module on the very same command line and it throws the same ImportError again. I listed installed modules using pip freeze and I didn't find the module listed there. Before this, all the third-party libraries like crispy-forms, pagedown were working fine. Any help would be highly appreciated. -
Switch to URL in another language with Django: slug + kwargs
I have a site in different languages with the slugs translated and working fine. My issue is that for one page I am not able to switch from one language to another one. Having: #urls.py urlpatterns += i18n_patterns( ... url(_(r'^travel/from-(?P<orig_city>[a-z\-\(\)_]+)-to-(?P<dest_city>[a-z\-\(\)_]+)$'), results_views.route, name='route'), ... ) One example of urls would look like this: en/travel/from-munich-to-london for the English version de/reisen/von-muenchen-nach-london for the German version Note the 3 factors involved: language code at the beginning of the url slug translation (from --> von, to --> nach) kwargs: orig_city, dest_city As I said, I would like that from the English version one can go directly to the German version of the same page (not to the home page). So far I have seen proposals that enable to switch the language code at the url (point 1 above). For instance from en/travel/from-munich-to-London to de/travel/from-munich-to-london. But I have not found out how to combine that with the translation of the slug (point 2 above) AND especially with the use of kwargs (point 3 above). I liked the idea of using a templatetag, as suggested here and here, but when using it in the template: {% translate_url de %} or {% translate_url de orig_city dest_city %} I … -
pass environment variable from django to react app
I would like to pass a variable from django to react app. I know I can do it by passing window object from html page but I would like to know if its possible to do it using environment variable. I came across this link How can I pass a variable from 'outside' to a react app? which mentions using .env file. Please advise on how it can be used with Django/Python setup. -
Using materialize CSS datepicker with django form
I am writing an application using Django and am using Materialize CSS. I have one view using the CreateView template for a class with a DateField. I am using django-materializecss-form to format. The form displays correctly, including the datepicker, and everything seems to work, but the date field never successfully validates. Upon closer inspection, it seems that the datepicker never sets the value for the input. Django 1.11, MaterializeCSS 0.99.0 -
Redirect while passing message in django
I'm trying to run a redirect after I check to see if the user_settings exist for a user (if they don't exist - the user is taken to the form to input and save them). I want to redirect the user to the appropriate form and give them the message that they have to 'save their settings', so they know why they are being redirected. The function looks like this: def trip_email(request): try: user_settings = Settings.objects.get(user_id=request.user.id) except Exception as e: messages.error(request, 'Please save your settings before you print mileage!') return redirect('user_settings') This function checks user settings and redirects me appropriately - but the message never appears at the top of the template. You may first think: "Are messages setup in your Django correctly?" I have other functions where I use messages that are not redirects, the messages display as expected in the template there without issue. Messages are integrated into my template appropriately and work. Only when I use redirect do I not see the messages I am sending. If I use render like the following, I see the message (but of course, the URL doesn't change - which I would like to happen). def trip_email(request): try: user_settings = Settings.objects.get(user_id=request.user.id) … -
Django TypeError admin panel
my admin block is not working and giving TypeError was working properly until i added base template to my code from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('blog.urls')), ]