Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to install ASKBOT in a jailed virtualhost on Ubuntu14
[Ubuntu14.04, Apache2.4, MariaDB, Python 2.7] I am in the process of setting up ASKBOT on one of my jailed virtual hosts. I have setup the jail with a ssh user, which can run Python 2.7, use virtualenvwrapper, and am able to connect to my MariaDB server through 127.0.0.1 rather than localhost. Tested and working. To install ASKBOT, I used pip install askbot and after it installed a bunch of stuff (including DJango 1.8 and a 15MB Pillow), the installer now wants to compile regex_2/_regex.c but complained it couldn't find x86_64-linux-gnu-gcc. This is a bit of a surprise because I'm not that excited about setting up GCC inside the jail. Would anyone be able to recommend what I should do at this point? -
How to interpret python code in dJango when trying to open files?
I have below codes written in python in Django. Since I am new to jango and python, I have a hard time understanding below code. What makes me understand hard is that the function process(f) inside in the for-loop. why does it have to be inside the for-loop? def Upload(request): for count,x in enumerate(request.FILES.getlist("files")): def process(f): with open('/Users/sclee/PycharmProjects/uploadFile/bin/upload/media/file_' + str(count),'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) process(x) return HttpResponse("File(s) uploaded") -
django media file not found 404
I have a django blog application wherein while posting a blog, a file can be attached and submit as well. Here is the views.py code: def user_own_blog(request): if request.method == 'POST' and request.FILES['blog_document']: title_b = request.POST.get('blog_title') content_b = request.POST.get('blog_content') file1 = request.FILES['blog_document'] fs = FileSystemStorage() document_name = fs.save(file1.name, file1) uploaded_document_url = fs.url(document_name) b = Blog(title=title_b, content=content_b, blog_document=uploaded_document_url) b.save() return render(request, 'mysite/portfolio.html') else: return render(request, 'mysite/blog.html') And here is the MEDIA_ROOT and MEDIA_URL path names: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = '/Users/xyz/BlogApplication/mysite/media' And following is the code for urls.py inside mysite app: urlpatterns=[ ..... ...... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is the project structure, wherein I need the media folder to be present inside the 'mysite' app instead of directly under the BlogApplication While the file is getting uploaded successfully, it shows up as follows in the /api And on clicking the file link: the 404 not found error occurs. I think the MEDIA_ROOT file name is not correct. Please help! Thanks in advance. -
how to get all programs at lms side openedx
I am having an issue on displaying programs at lms side in ginkgo version. I have added programs from course discovery in which api also sends data to lms and i am getting specific programs 'about page' but not able to find all programs.Where can i get list of all programs in which i have not enrolled?Do i need to enable eCommerce functionality for that? I have followed this links Visit https://groups.google.com/forum/#!topic/openedx-ops/ImtlSrCtvMo Thank You. -
How to increment a value in postgres with an update query (python)
I'd like to run a one-line update query (using Python and Postgres) that increments a value by 1. Whats the most efficient way to do that? I thought that ideally it would look like this (in my Django Views.py file): def login_user(request): UserProfile.objects.filter(username=username).update(logins += 1) BUT because of the ' += ', that code gives me this SyntaxError: invalid syntax - which is odd because I thought += was legitimate python (see here). Surely there is a more efficient way to increment a value in postgres than this (which does work): def login_user(request): thing = UserProfile.objects.filter(username=username).values("logins") # gets the initial value total_logins = int(thing[0]['logins'])+1 # adds 1 to that value UserProfile.objects.filter(username=username).update(logins = total_logins) # Updates the value in the database I have found similar solutions on StackOverflow but their answers gave SQL queries instead of python queries. - Thanks in advance! -
unable to import a file to a to a python script and to log the print statement to another file using command line argument
i want to import a .py file lets say param.py (which has some variable),through command line argument, also i want to redirect print statement of a main file let say test.py to a file.Also i want to use param.py variables to test.py script.Can anyone help me with this?here is my code. For param.py target_mac = "000000000000FFFF" ACEM1_slave="20" ACEM2_slave="11" DCEM_slave="50" For test.py `//Please add the code, as per my requirement.` I want to pass the argument in command line as: py test.py -f param.py -o out.txt where, test.py is the main file,param.py is the config file. & out.txt is the log file. Thank you. -
how to test django fixture json file
I has a script that will generate a JSON file (let me call it data.json) that for my django application, usually I can test it by running command python manage.py testserver data.json However, I would like to run this thing in unit tests rather than run this through shell (because it would start a server and never return back to the shell). I don't need to run any tests that depends on this fixture. I only want to make sure that the fixture generated can be loaded. -
Changing a Django model from ForeignKey to ManytoMany getting Invalid field name(s) given in select_related: 'group'. Choices are: user
I want to change my post models. Before I had a very simple relation. There are 3 models User, Post and Group. A user can create posts and the post has to belong to 1 group. example: The user Samir wrote a post on Football. This post belongs to the group Sports. Below is how the models look Earlier Model: class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) I want to change this such that each post can belong to a maximum of 3 and minimum of 1 group. Below is my model class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ManyToManyField(Group, related_name='posts', max_length=3) title = models.CharField(max_length=250, unique=True) The post is created successfully but does not redirect to the post detail page and gives the below error. Also in the django admin the group in posts is blank. Below is my DetailView My Views are: from braces.views import SelectRelatedMixin class PostDetail(SelectRelatedMixin, DetailView): model = Post select_related = ('user', 'group') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user__username__iexact=self.kwargs.get('username')) def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data() context['form'] = EventForm try: context['event'] = Event.objects.filter(post__slug=self.kwargs.get('slug')) except Event.DoesNotExist: context['event'] = None return context My Url for the DetailView is: url(r'^(?P<username>[-\w]+)/(?P<slug>[-\w]+)/$', β¦ -
i'm use djang custom backend check JWTtoken has error: userprofile matching query not existing?
i'm use djang rest framework JWTtoken has error: userprofile matching query not existing, i check code and not found the error is where. after debug is get the msg: { "non_field_errors": [ "Unable to login with the authentication information providedγ" ] } -
Is it safe/necessary to use elastic beanstalk CNAME in Django allowed URLβS
Part One: I am setting up a Django application on AWS for the first time and was wondering what the common practice is for domain/Django security elements. I have both my primary domain and elastic CNAME in allowed hosts. Is that okay? Part Two: Is making a www CNAME (www.domain.com) and pointing it to my elastic CNAME bad practice? -
Create Pie Chart using Ploytly and display in django templates
I'm working on a project using Python(3.6) and Django in which I need to create a pie chart using the plotly library. I have labesl and values but it returns an error. My labels: ['WD', 'NY', 'LA', 'ID', 'DE', 'CO', 'NE', 'OK', 'UT', 'SD', 'ID\n'] My values: [0.2139917695473251, 0.18152720621856425, 0.17329675354366714, 0.1545496113397348, 0.07315957933241884, 0.07315957933241884, 0.0722450845907636, 0.037951531778692274, 0.010973936899862825, 0.0054869684499314125, 0.003657978966620942] I the returns the error below: File "/Users/abdul/PycharmProjects/Dmitry/DVirEnv/lib/python3.6/site-packages/plotly/tools.py", line 1501, in return_figure_from_figure_or_data raise exceptions.PlotlyError("The figure_or_data positional " plotly.exceptions.PlotlyError: The figure_or_data positional argument must be dict-like, list-like, or an instance of plotly.graph_objs.Figure -
Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': '', 'token': ''}' not found
urls.py app_name='user' urlpatterns = [ re_path(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',auth_views.PasswordResetConfirmView.as_view(template_name='user/password_reset_confirm.html'), name='password_reset_confirm'), ] template {{ protocol }}://{{ domain }}{% url 'user:password_reset_confirm' uidb64=uid token=token %} shows the following error: Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': '', 'token': ''}' not found. 1 pattern(s) tried: ['user/reset/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] -
How to join table if string field is not null
I have to show all articles from a law. Besides that, each article can have a description or not. I have to show all articles and yours description, but I dont know how to join descriptions and article when description is not null. my view: def details(request, pk): law = get_object_or_404(Law, pk=pk) articles = Article.objects.filter(law=pk) articles = ( Article .objects .filter(law=pk) .annotate( is_marked=Exists( Highlight .objects .filter( article_id=OuterRef('id'), user=request.user ) ) ) ) context = { 'articles': articles, } template_name = 'leis/details.html' return render(request, template_name, context) My detail.html: <div class="article-post"> {% for article in articles %} {{article}} {% endfor %} </div> That's my model: class Law(models.Model): name = models.CharField('Name', max_length=100) description = models.TextField('Description', blank = True, null=True) class Article(models.Model): article = models.TextField('Artigo/Inciso') number = models.IntegerField('Number', blank=True, null=True) law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Law', related_name='articles') This class is saved with description made by a specific user in a specific article in a specif law: class Highlight(models.Model): law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Law', related_name='highlightArticles') article = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Article', related_name='highlightLaw') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='highlightUsers', related_name='highlightUsers') is_marked = models.BooleanField('Is it marked?', blank=True, default=False) description = models.TextField('Description', blank = True, null=True) How can I join the tables to show all the articles with yours specific description β¦ -
<Django newbie> Package for gallery management?
I'm planning to develop my first django site (actually first time to use a CMS rather than doing everything myself). It's intended for smartphones, with the main page based around the following paradigm: https://farm5.staticflickr.com/4890/32310524928_ef77dfdf47_c.jpg Think of it like a package management system with optional pictures and content / information tagged at each stop, and to which users can add new stop-records that contain their own pictures / videos / content. Not exactly, but that's a close enough analogy. The top frame, as noted, contains an image gallery that one can scroll through. It doesn't need to be in exactly this format, but roughly this format - a large image or video (optionally full-screenable), and you can click (or optionally swipe) to go to the next or previous one. I figured I should check out to see what packages are available for this (to handle uploads, thumbnails, etc). I found this comparison site: https://djangopackages.org/grids/g/gallery/ ... but there's really only two with any decent number of users and features (and only one is Python 3, which I prefer to work in). Neither really look to be what I'm looking for. For example, Photologue looks to be a sort of Flickr / Photobucket β¦ -
Importing CSVs to Postgresql django
Trying to implement solution from Import CSV to Postgresql but while closing(connecitions...) throws an error. What exactly am I doing wrong? Code: def import_csv(request): var = ['passing', 'rushing', 'receiving', 'defense', 'kicking', 'punting', 'returning', 'givetake'] for i in range(len(var)): file = f'../{var[i]}_stats.csv' with open(file, 'rb') as csvfile: columns = csvfile.readline().split(',') with closing(connections['my_database'].cursor()) as cursor: cursor.copy_from( file=csvfile, table=f'my_csv_{var[i]}', sep='|', columns=(columns) ), return print("Done!") -
Adapting jQuery ajax POST request into Fetch POST
I asked a separate SO question about doing a POST request via the fetch API, which properly includes a Django CSRF token I got a reply with jQuery code that I was able to get working. It looks like this: $.ajax({ type: 'POST', data: JSON.stringify(myData), contentType: 'application/json', url: myUrl, headers: { 'X-CSRFToken': csrftoken }, success: function(j) { console.log('success'); } }) I have not been able to adapt this into a fetch POST request. Can someone tell me what is wrong/missing with my code? It should do the same thing as the jQuery code. fetch(myUrl, { method: "POST", headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRF-Token": csrftoken, "Content-Type": "application/json; charset=utf-8", }, credentials: "same-origin", body: JSON.stringify(myData) }); (Note: myUrl, myData and csrftoken are defined earlier). -
Django & Postgres - how can I track down this performance slowdown?
I am trying to diagnose a performance issue in a Django application. The Postgres database is running on a remote server in the cloud, the Django server is running on my local OSX machine. The database has only about 2 records in it. This log output shows that the request commences with 2.8 seconds doing something. DEBUG = False in settings.py Changing CONN_MAX_AGE seems to make no difference. How can I track down exactly what it is doing in that time? I have suspected that it is creating a database connection but I can't seem to find a way to precisely watch connection creation requests between Django and Postgres. Here is the application output log when executing the view function that starts slow. The first and second milliseconds output are the same database request repeated. [04/Dec/2018 22:30:14] "GET /main/contact/gsnkn6/view/ HTTP/1.1" 200 7309 start [] milliseconds: 2783 [] milliseconds: 407 milliseconds: 0 milliseconds: 0 Here is the code of the Django view function: @require_http_methods(['GET']) @csrf_exempt def contact_view(request, contact_slug): print('start') start = datetime.datetime.now() contact = Contact.objects.get(slug=contact_slug) print(connection.queries) end = datetime.datetime.now() delta = end - start print(f'milliseconds: ', int(delta.total_seconds() * 1000)) start = datetime.datetime.now() try: contact = Contact.objects.get(slug=contact_slug) print(connection.queries) except Contact.DoesNotExist: return HttpResponseNotFound('404 β¦ -
Webrtc setup with Django
I'm building a new project that will require instant messaging, voip and video calls, the client will be implemented with reactnative for iOS and Android. Please how can I implement this into my django project. Thanks -
How to get a webpack files(bundled files)?
Folder Tree Cebula4 -back -front -static -bundles -MainPage.js (bundled by `webpack`) I'd like to get MainPage.js file in my main.html However, there is always an error, Not found (404). I think I misunderstand how I can get the path of webpack-files. Here are some my codes related with this problem. (I used Django on backend and react on frontend) Settings.py ... WEBPACK_LOADER = { 'DEFAULT' : { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'front/webpack-stats.json'), } } STATIC_URL = '/front/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'front/static'), ] STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') ... The image for Error -
Django user groups login check
I created a group as a users for my django project. I want to create users with no admin permission. I just want them to be able to log-in website. I have a form, I want that only users can fill this form. So I want to check if they are logged in or not. Is it possible? -
trying to run MOBSF but nothing appear
I am trying to work on MOBSF in order to test the security of specific mobile apps, I download the source and when type (python manage.py runserver) I get access to the IP but all I get as in the picture, no images,colors or anything else, pleas help how can I solve the problem?MOBSF when run the server The error I get -
Travis Error doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am trying to build my app in Travis but I keep getting the following error which I am unable to debug. Can anybody see anything obvious that I may be doing wrong? RuntimeError: Model class Code-Institute-Milestone-Project-05.babysitters.models.Babysitter doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. INSTALLED_APPS = [ 'about', 'accounts', 'blog', 'bookings', 'babysitters', 'contact', 'checkout', 'storages', 'django.contrib.admin', 'django.contrib.humanize', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'django_gravatar', 'home', -
Django input login for an admin
How can i add attribute autocomplete="off" to the input login template form for an admin ? I'm find this in the login.html template but can`t find where is the form template <div class="form-row"> {{ form.username.errors }} {{ form.username.label_tag }} {{ form.username }} </div> -
Unable to create custom user model with Django 2.1 and Python 3.5
I'm trying to create a custom user model (as I've done several times before) in an attempt to remove the "username" field and replace it with the "email" field. I created a brand new project and installed the latest version of all packages in a venv: Django==2.1.4 django-filter==2.0.0 djangorestframework==3.9.0 Markdown==3.0.1 pkg-resources==0.0.0 pytz==2018.7 I then created a project with the following layout: . βββ api β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ tests.py β βββ views.py βββ manage.py βββ penguin_backend βββ __init__.py βββ settings.py βββ urls.py βββ wsgi.py I then added the following code to the api/models.py file which replaces the default user model and user manager class: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.core.mail import send_mail from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) β¦ -
Ajax making two GET requests when it should when it should only be one.
Ajax call is making two GET requests, only for zip codes beginning and ending with 0. It uses jQuery to get the value of the zip field checks the value to see if it equals 5, then makes the get request to a Django view in the second block of code. A success in the Ajax calls iterates through the list and displays it on the webpage. The problem is that it should only be one GET request, but again sometimes it makes two... $( "#zip" ).keyup(function() { if ($(this).val().length===5){ var zip = $(this).val() $.ajax({ type: 'GET', url: '/zipcode', data: { number: $(this).val(), }, dataType: "json", success: function(data) { $(".zip_response").remove(); var zipList = JSON.parse(data); var container = $('<div />'); for(var j=0; j< zipList.length; j++){ container.append($('<li href="#" />').addClass("zip_response").text(zipList[j]["city"]+','+zipList[j]["state"])); } $('.zip_menu').append(container); $('.zip_menu').show(); }, error: function (errorThrown) { }, }); } }); This takes the zip code makes a database call and either returns the row(s) if it exists or returns "None" for city and state info. def zipcode(request): if request.is_ajax(): number = int(request.GET['number']) zip_list = Zip.objects.raw('SELECT * FROM users_zip WHERE zip_code = %s', [number]) data=[] for item in zip_list: data.append({'city': item.city, 'state': item.state}) json_data = json.dumps(data) if not data: json_data = json.dumps([{'city': β¦