Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am attempting to use .latest() to retrieve the most recent object but I am getting field error and an extra "-"
The code seems pretty innocuous: home_post = Post.objects.latest('-timestamp') but it returns the following error: FieldError at / Invalid order_by arguments: ['--timestamp'] There seems to be an extra "-" that isn't in my code. Where is this coming from? Is sublime adding this? Is this what is actually causing the error? -
Django ImportError: cannot import name
I have an application notes and model name defined as notes/models.py from shorturls.models import ShortUrl class Note(models.Model): # columns here def __str___(self): return self.title def post_save_note_receiver(sender, instance, created, *args, **kwargs): if instance and created: ShortUrl.objects.create(note=instance) and another app shorturls to store short URL for each record with model shorturls/models.py from notes.models import Note class ShortUrl(models.Model): note = models.OneToOneField(Note, on_delete=models.CASCADE, blank=True) short_key = models.CharField() def __str__(self): return self.short_key @receiver(pre_save, sender=ShortUrl) def pre_save_short_url_receiver(sender, instance, *args, **kwargs): instance.short_key = unique_short_key_generator(instance) @receiver(post_save, sender=Note) But on python manage.py makemigrations, It gives error as File "path_to_app/shorturls/models.py", line 7, in <module> from notes.models import Note ImportError: cannot import name 'Note' -
Angular - lazy loading from custom folder
I have Angular 4 application with several lazy loaded modules. I working as expected as standalone (in local development server), however when I try to deploy it using Django application... Main page - index.html is generated by Django view from the built index.html by angular-cli, all pathing to bundle.js files are adjusted to use static content pathing and all is working until I try to lazy load... It tries to find file 0.*****.js in a root directory, where the file is not, because is in static content location... Changing <base href="/static/"> would load lazy file(s) but would also change the whole url and corrupt routing... (I am also looking to static content be on external server) How I can adjust path there files to be lazy load (0.*****.js) are located without changing <base href="/static/"> ? -
Copy data from Django Form to Django Model so it can be saved to the database
I am using the Wizard Form Tools to gather information from users by using a sequence of screens. I followed the information below. http://django-formtools.readthedocs.io/en/latest/wizard.html https://github.com/django/django formtools/blob/master/docs/wizard.rst In my case, I am using 4 forms controlled by the Wizard. One of the forms looks like the following: forms.py class OwnerStep1( forms.Form ): contactsalutationid = forms.ModelChoiceField(queryset=Mstrgensalutationtype.objects.all(), label="Salutation") contactfirstname =forms.CharField(label="First Name") contactlastname =forms.CharField(label="Last Name") contactofficephoneno =forms.CharField( label="Office Phone No.") contactcellphoneno =forms.CharField( label="Cell Phone No") I saw in the documentation, that one could use the following to get the data out of the form: views.py class OwnerCollectDataView( SessionWizardView ): template_name = 'authorization/collect_owner_data_form.html' def done(self, form_list, **kwargs): for form in form_list: hold = self.get_form_step_data(form) [... snip ...] The results I have are in the attachment What I am seeking now is to copy this information (in the variable "hold") into Model so that that it can be stored in the database. The model I have looks like the following: models.py class Mstrstorehead(models.Model): [... snip ...] companyname = models.CharField(max_length=30, blank=True, null=True, verbose_name="Company Name") businesstypeid = models.ForeignKey(Mstrgenbusinesstype, models.DO_NOTHING, db_column='businesstypeid', blank=True, null=True, verbose_name="Business Type") ourmission = models.CharField(max_length=200, blank=True, null=True, verbose_name="Our Mission") contactsalutationid = models.ForeignKey(Mstrgensalutationtype, models.DO_NOTHING, db_column='contactsalutationid', blank=True, null=True, verbose_name="Salutation") contactfirstname = models.CharField(max_length=20, blank=True, null=True, verbose_name="First Name") contactlastname = … -
Flush particular session in Django
How can I clear particular session variable ? Official docs talk about using .flush() as in request.session.flush() but I noticed it doesn't only clear that particular session, it clears also my session in admin as superuser. I really don't like the idea of me and my mates working in admin or whatnot while users logging in and out and logging us out at the same time. There must be better way. I tried del the session variable but somehow it still remembers it after refresh. What is the right way to do it ? -
Add username to URL with AuthenticationForm FormView
I'm coming from Laravel and new to Django. I'm trying to add a username to the url after login. This has been asked before a few times, but I have yet to make the solutions work (they involve having a model attached to the generic FormView class). Here is what I have: urls.py path('login/', views.Login.as_view(), name='login'), # Logged in user path('home/<str:username>', views.UserIndex.as_view(), name='user_index'), views.py class Login(views.AnonymousRequiredMixin, views.FormValidMessageMixin, generic.FormView): authenticated_redirect_url = '/' form_class = LoginForm form_valid_message = "You have successfully logged in" template_name = 'pythonmodels/registration/login.html' success_url = reverse_lazy('pythonmodels:user_index', args=("Bill",)) def form_valid(self, form): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(self.request, user) return super(Login, self).form_valid(form) else: return self.form_invalid(form) forms.py class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'username', 'password', ButtonHolder( Submit('login', 'Login', css_class='btn-primary') ) ) In the views.py file, I would like the args for success_url to be the username of the user that was just authenticated. Should this be done in the LoginForm class? I have also seen that you can go to an intermediate url and then get the User data, but this seems like a terrible extra step. I would like to … -
Django is not going to directed url
im a beginner and am following a tutorial online. i tried to duplicate what the instructor on my how however its not working and i dont know why. if you guys could help that'd be really appreciated. I run server and go to the homepage which in this case is just http://127.0.0.1:8000/ but then when i go to http://127.0.0.1:8000/signups, nothing seems to happen, it just continues to show the home page. No Errors show here are my relevant files: App Level-------- AppThree/forms.py file from django import forms from AppThree.models import User # Create your models here. class NewUserSignUp(forms.ModelForm): class Meta: model = User fields = '__all__' AppThree/models.py from django.db import models # Create your models here. class User(models.Model): firstName = models.CharField(max_length=125) lastName = models.CharField(max_length = 125) email = models.EmailField(unique=True, max_length=265) AppThree/urls.py from django.conf.urls import url from AppThree import views urlpatterns = [ url(r'^$', views.NewUserSignUp, name='NewUserSignUp'), ] AppThree/views.py from django.shortcuts import render from AppThree.forms import NewUserSignUp # Create your views here. def home(request): return render(request, 'AppThree/home.html') def NewUserSignUp(request): form = NewUserSignUp() if request.method == "POST": form = NewUserSignUp(request.POST) if form.is_valid(): form.save(commit=True) return home(request) print("Validation Success") else: print("Error") return render(request, 'AppThree/SignUp.html',{'form':form}) End app Level -------------- Project level ---------- ProThree/urls.py from django.conf.urls import … -
Tell Django to use test database created by Pytest
I am currently running pytest with my Django project. When I first start executing my tests, a test database correctly gets created. I have verified this. However, the Django application code is using the database specified in settings.py for its queries. How can I force my Django application to query my test database during pytest? Here are my tests so far. django.setup() pytestmark = pytest.mark.django_db TEST_DIR = os.path.dirname(os.path.abspath(__file__)) XML_DIR = os.path.join(TEST_DIR, 'xml/') BASE_URL = 'http://127.0.0.1:8000' @pytest.fixture(scope="module") def database_ready(): create_customers(5) create_dr_programs(2) create_sites(2) create_dr_events(5) yield def to_no_space_string(string): return ''.join(string.split()) def compare_xml_strings(one, two): return to_no_space_string(one) == to_no_space_string(two) def get_file_xml(filename): ''' :param filename: the filename, without the .xml suffix, in the tests/xml directory :return: returns the specified file's xml ''' file = os.path.join(XML_DIR, filename + '.xml') with open(file, 'r') as f: xml = f.read() return xml @pytest.mark.django_db def test_no_events(database_ready): vtn_response_xml = get_file_xml('vtn_response_no_events') poll_xml = get_file_xml('ven_poll') time.sleep(5) response = requests.post(POLL_URL, data=poll_xml, headers={'Content-Type': 'application/xml'}) print(response.content.decode('utf-8')) assert (compare_xml_strings(vtn_response_xml, response.content.decode('utf-8')) is True) Thanks! -
django - linking the register form info to user profile model
I am trying to make a webapp that includes register/login operations. The login is working fine but the registration form is frustrating. I have a class registration form that inherits from UserCreationForm. The users are created and seen in the admin page when created but the problem I am having is not being able to see them in my UserProfile model in the admin page. It does not link the information and I could not find a way the link them. Here is the registration form: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) city = forms.CharField(required=False) country = forms.CharField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) username = forms.CharField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'country', 'city', 'email' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) #user.first_name = self.cleaned_data['first_name'] if commit: user.save() return user Here are my models: class UserModel(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) username = models.TextField(max_length=30, default="") first_name = models.TextField(max_length=30, default="") last_name = models.TextField(max_length=30, default="") country = models.TextField(max_length=30, default="Which country are you from?") city = models.TextField(max_length=30, default="Which city are you from?") class ColorChoice(models.Model): user = models.ForeignKey( 'UserModel', on_delete=models.CASCADE ) color1 = models.IntegerField() color2 … -
Make active class only visible when the button is clicked
I have 2 buttons that pop a modal and they are highlighted whenever they are clicked, but the first button is already highlighted by default even tho the modal is closed when the page loads. My goal is to remove the class="active" for the default state, add it when the buttons are clicked and remove it when the modal is closed. What's the easier way of doing it? Here's my HTMl: <div class="assistance-body"> <nav style="width: 20%; float: right;"> <ul class="nav nav-tabs nav-justified"> {% for key, data in resources %} <li{% if loop.first %} class="active"{% endif %}> <a data-toggle="tab" href="#{{ key }}" segment-event="Modules: Tutor: Clicked {{ key|capitalize }} Section" segment-not-track-if-class="active" onclick="openAssistance()" > <i class="icon-{{ key }} icon-sm"></i> <span class="sr-only">{{ ('resources.tabs.' ~ key ~ '.title') | trans }}</span> </a> </li> {% endfor %} </ul> </nav> <div class="assistance" id="assistance" style="display: none;"> <button type="button" class="close" toggle-class="oc-open" onclick="closeAssistance()" aria-hidden="true">&times;</button> <div class="tab-content" style="display: block; z-index: 10; "> {% for key, data in resources %} <div class="tab-pane{% if loop.first %} active{% endif %}" id="{{ key }}"> {% include data.view with { 'category': data.category, 'resources': data.resources } %} </div> {% endfor %} </div> </div> </div> -
Printing to PDF a Django Template using Google Chrome Remote interface
I have a Django Server (Django==1.11.7) This Django server runs on a VM ( myvm ) and I access it's content from the host machine ( Not really relevant, just to give some content what myvm means ) This Django server serves a template. Inside this template, I reference some static files. For example: <link rel="stylesheet" href="http://myvm:8080/static/css/mycss.css"> <img src="http://myvm:8080/static/images/myimage.png"> If I curl or request these files from python for example, it works, both from my host machine and the vm. requests.get("http://myvm:8080/static/css/mycss.css").text That for example returns the expected content. In the browser, the HTML renders correctly. Accessing my Django server both from the host and the vm results in a perfectly good page. More over, copying the source code of the page and accessing the file also renders correctly. For example, if I literally copy paste the source from the browser into mysite.html and look at that, file:///some/local/path/mysite.html that also renders correctly. Looking in the Django logs, I see messages like this: [15/Dec/2017 00:00:00 - 1513349355] INFO [django.server:124] "GET /static/images/myimage.png HTTP/1.1" 200 68 The same for css or scripts. The static file mysite.html sees references to files on that server, requests them, and it receives them successfully. The exact same thing … -
django auto convert image to png
I have created a multi image upload form in a Django where the user can upload personal images to his/her profile. I want to find/create a python function where convert the original image from user to png and that new convert image update the png_image field from my model.any idea how to do that? Wow to do this automate for any image upload? models.py class MyModel(models.Model): name = models.TextField() slug_name = models.SlugField() user = models.ForeignKey(User, unique=False) original_image = models.ImageField(upload_to=directory_path) png_image = models.ImageField(upload_to=directory_path) views.py def dataset(request): uploadimages = UploadImagesForm(request.POST or None, request.FILES or None) if uploadimages.is_valid(): if request.FILES.get('multipleimages', None) is not None: images = request.FILES.getlist('multipleimages') for image in images: ........... -
How can I load a class based view by slug?
I've created a view to edit a user: class UsersEditView(UpdateView): model = User fields = ['first_name', 'last_name', 'email', 'password'] success_url = reverse('user-list') which edits this model: class User(AbstractUser): email = EmailField(unique=True) slug = AutoSlugField(populate_from='email', max_length=10, unique=True) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' I defined the url this way: urlpatterns = [ path('', UsersListView.as_view(), name='user-list'), path('new/', UsersCreateView.as_view(), name='user-new'), path('edit/<str:slug>/', UsersEditView.as_view(), name='user-edit') ] and I test it like this: class EditUserTest(AbstractTest): @classmethod def setUpClass(cls): super().setUpClass() user = User(email='email@provider', first_name='Test', last_name='User', slug='slug', password='qqq') user.save() def test_edit_user(self): response = EditUserTest.client.get(reverse('user-edit', args=('slug', ))) except response is always 404: ipdb> response.status_code 404 So, what am I missing? This is for Django 2.0. -
Local Package - Error : File does not exist
When I install pip install -e git+ssh://git@gitlab.com/p39/lib-p39.git@de5622dcf0b9a084f9b0a34cdd1d932026904370#egg=p39 my program is able to find the files needed. However, if I want to make changes locally and install the same library with pip install -e ~/Projects/Work_Projects/BP/lib-p39 I got the following traceback Template Loader Error: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /home/infinity/Projects/Work_Projects/Budget_Propane/clients-budgetpropane-com/zoneclient/templates/zoneclient/dashboard.html (File does not exist) Using loader django.template.loaders.app_directories.Loader: /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/django/contrib/auth/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/grappelli/dashboard/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/grappelli/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/django/contrib/admin/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/grappellifit/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/dajaxice/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/p39/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/paypal/standard/ipn/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/guardian/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/userena/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/crispy_forms/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/bootstrap_ui/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/captcha/templates/zoneclient/dashboard.html (File does not exist) /home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/rest_framework/templates/zoneclient/dashboard.html (File does not exist) Traceback: File "/home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 137. response = response.render() File "/home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/django/template/response.py" in render 103. self.content = self.rendered_content File "/home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content 78. template = self.resolve_template(self.template_name) File "/home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/django/template/response.py" in resolve_template 54. return loader.select_template(template) File "/home/infinity/.virtualenvs/p39-1/local/lib/python2.7/site-packages/django/template/loader.py" in select_template 194. raise TemplateDoesNotExist(', '.join(not_found)) Exception Type: TemplateDoesNotExist at /dashboard Exception Value: zoneclient/dashboard.html How could I fix my problem? -
Python https request on Facebook api
I have a problem on my server. I use Django rest framework on a linux server. And I need to check the Facebook token recieved from the client (a mobile app). Sometimes, not all the time, i recieve this bad response : ('bad handshake: SysCallError(0, None)',) My code is : try: requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'DES-CBC3-SHA' response = requests.get('https://graph.facebook.com/me?fields=first_name,last_name,gender,email,verified&access_token=' + token, verify=False) except Exception as e: logger.error(str(e)) return Response(str(e), status=status.HTTP_403_FORBIDDEN) Anyone know what i need to do to resolve this error? Thanks a lot for your answers. -
psycopg2.OperationalError: FATAL: role "postgresql" does not exist
I am a postresql novice. When I was ready to migrate INSTALLED_APPS in 'settings' to database,there appeared the following error: psycopg2.OperationalError: FATAL: role "postgresql" does not exist and I have displayed the full exception message: c:\fanhuaxiu\Scripts>activate (fanhuaxiu) c:\fanhuaxiu\Scripts>cd .. (fanhuaxiu) c:\fanhuaxiu>cd fhx (fanhuaxiu) c:\fanhuaxiu\fhx>python manage.py migrate Traceback (most recent call last): File "C:\fanhuaxiu\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\fanhuaxiu\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\fanhuaxiu\lib\site-packages\django\db\backends\postgresql\base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "C:\fanhuaxiu\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: role "postgresql" does not exist It has taken me nearly 2 hours to find a solution and failed 233333. Thanks in advance. -
how to avoid circular django model import?
I have these models below # user profile models file from ad.models import FavoriteAd class UserProfile(models.Model): def get_user_favorite_ad(self): return FavoriteAd.objects.filter(fav_user=self) # ad models file from user_profile.models import UserProfile class FavoriteAd(models.Model): fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE) I have tried using these but it give me the NameError UserProfile not found # ad models files class FavoriteAd(models.Model): fav_user = models.ForeignKey('user_profile.UserProfile', blank=False, on_delete=models.CASCADE) Also tried these as well still got error that model are not ready # ad models files from django.apps import apps UserProfile = apps.get_model('user_profile', 'UserProfile') class FavoriteAd(models.Model): fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE) -
Relating a model on a foreign key
I have the following custom User model. It has a field coid that i'd like to relate to my facility dimension table. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_cfo = models.BooleanField(default=False) facility = models.CharField(max_length=140) officename = models.CharField(max_length=100) jobdescription = models.CharField(max_length=140) positioncode = models.CharField(max_length = 100) positiondescription = models.CharField(max_length=140) coid = models.CharField(max_length=5) streetaddress = models.CharField(max_length=140) title = models.CharField(max_length=100) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); def get_short_name(self): return self.username I've defined the foreignkey in my Facility_Dimension table, but it's trying to create the relationship on formattedusername. class FacilityDimension(models.Model): unit_num = models.CharField(db_column='Unit_Num', max_length=5, blank=True, null=True) # Field name made lowercase. company_code = models.CharField(db_column='Company_Code', max_length=1, blank=True, null=True) # Field name made lowercase. coid = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='Coid',primary_key=True, serialize=False, max_length=5) # Field name made lowercase. coid_name = models.CharField(db_column='COID_Name', max_length=50, blank=True, null=True) # Field name made lowercase. c_level = models.CharField(db_column='C_Level', max_length=6, blank=True, null=True) # Field name made lowercase. company_name = models.CharField(db_column='Company_Name', max_length=50, blank=True, null=True) # Field name made lowercase. s_level = models.CharField(db_column='S_Level', max_length=6, blank=True, null=True) … -
cannot start gunicron on server in django project
I've been going through the process of creating a django project on my ubuntu server and I reached gunicorn start but i am getting this erorr: gunicorn projectname.wsgi [2017-12-15 00:12:32 +0000] [32264] [INFO] Starting gunicorn 19.7.1 [2017-12-15 00:12:32 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:32 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:33 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:33 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:34 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:34 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:35 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:35 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:36 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:36 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:37 +0000] [32264] [ERROR] Can't connect to ('127.0.0.1', 8000) -
TypeError execute_sql() got an unexpected keyword argument 'chunk_size'
I try to run ldapdb with rest_framework and get an exception: Type: TypeError at /users/ Value: execute_sql() got an unexpected keyword argument 'chunk_size' Location: /usr/local/lib/python3.5/dist-packages/django/db/models/query.py in __iter__, line 54 models.py: import ldapdb.models from ldapdb.models.fields import CharField, IntegerField class User(ldapdb.models.Model): # LDAP meta-data base_dn = "ou=user,o=foo" object_classes = ['person'] # user attributes uid = CharField(db_column='uid', max_length=8, primary_key=True, unique=True) employeeID = IntegerField(db_column='employeeID', unique=True) def __str__(self): return self.uid def __unicode__(self): return self.uid serializers.py: from rest_framework import serializers from api.models import User class UserSerializer(serialisers.HyperlinkedModelSerializer): class Meta: model = User fields = ('uid', 'employeeID') views.py from rest_framework import generics from api.models import User from api.serializers import UserSerializer class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer urls.py from django.conf.urls import url from api import views urlpatterns = [ url(r'^users/$', views.UserList.as_view()), ] and last but not least pip freeze: Django==2.0 django-ldapdb==0.9.0 djangorestframework==3.7.3 -
Emails sent by django-allauth are not translated
I have translated my project to Spanish I have ran python manage.py makemessages -l es and python manage.py compilemessages -l es both. My project strings are properly translated and shown when user has language set to es, but emails from django-allauth are sent in English. What am I missing? Thanks in advance. -
Why is this Django-Channels consumer running synchronously?
My understanding of websockets and django-channels is very superficial, so please bear with me. Before testing a more serious use case, I'm trying to gradually append a piece of data to my HTML, using jquery and django-channels. Here's my app/consumers.py: @channel_session_user def ws_receive(message): user_group = str(message.user.username) user_profile = message.user.user_profile.id message_text = json.loads(message['text']) room = "pk" for i in range(1, 5): time.sleep(1) Group(user_group).send({'text': json.dumps(room)}) I have the jquery code successfully connecting to the websocket, and calling this consumer upon a button click. First identify the click: $('#search_button').on('click', function(e) { e.preventDefault(); // prevent form submission var myval = $('#qos').val(); console.log(myval); mysocket.send(JSON.stringify(myval)); }); Which triggers onmessage: mysocket.onmessage = function message(event) { var data = JSON.parse(event.data); console.log(data); if (data === 'pk') { console.log("True"); $('#result_div').append('<p>' + data + '</p>') } }; The problem is, All of the pk pargraphs (4 in total) are being "spit out" in one bunch to my page. I thought this: for i in range(1, 5): time.sleep(1) Group(user_group).send({'text': json.dumps(room)}) Is supposed to send the message one-by-one to the websocket, which should then also inject the HTML one by one..that's happening is that it's waiting ~5 seconds (number of loops), and then adding 5 pk paragraphs at once. What am I misunderstanding? … -
same name in INSTALLED_APPS for 3rd party lib
I have a project with 4 marketplaces one of which is Jet. Also I've got 'jet-admin' skin that I should add to INSTALLED_APPS as 'jet'. My marketplace app is defined as 'vmode.apps.marketplaces.jet'. There's a conflict between them and it's close to impossible to rename everything connected to marketplaces.jet. I guess that renaming 3rd party lib 'jet' is an option. I made some research and found that there's a label in AppConfig, so I tried to make class JetAppConfig(AppConfig): name = 'jet' label = 'jet_skin' and added to: INSTALLED_APS = [ 'vmode.apps.marketplaces.base.apps.JetAppConfig', 'vmode.apps.marketplaces.jet', ] after I made migrations it returned: CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0001_initial, 0002_delete_userdashboardmodule in jet_skin). To fix them run 'python manage.py makemigrations --merge' and after I made it returned: raise ValueError("Could not find common ancestor of %s" % migration_names) ValueError: Could not find common ancestor of set([u'0001_initial', u'0002_delete_userdashboardmodule']) How can I change lib name without touching marketplace.jet.models\migrations? Any help appreciated. -
Django application memory usage
I am running Django application (built on Django Rest Framework) on Digital Ocean server with following characteristics: 4gb RAM 2 CPUs 60 GB drive I am using Gunicorn to run Django app and Celery to manage queue. Database is MySQL. As I can see CPU usage is really low, but memory usage seems to be large. After I deploy I noticed that python3 process uses even more memory (something around 75%). Whenever I deploy I am running after_deploy script, which contains following: service nginx restart service gunicorn restart chmod +x /mnt/myapplication/current/myapplication/setup/restart.sh source /mnt/env/bin/activate cd /mnt/myapplication/current/ pip3 install -r requirements.txt python3 manage.py migrate --noinput >> /mnt/migrations/migrations.log rm -f celerybeat.pid rm -f celeryd.pid celery -A myapplication beat -l info -f /var/log/celery/celery.log --detach celery -A myapplication worker -l info -f /var/log/celery/celery.log --detach Are these numbers expected? And if not, how can I investigate what is going wrong? -
check file extension in html using jinja
i was working making a project using django and using jinja for template design. My questions:- i have a file in localhost server and i don't no what kind of file is that So how i choose tags in html to show the file means or . i searched in web and find out that i should upload my videos in youtube and insert the embedded url in html using tag. But i don't wanna do that .I want to save files on my server please provide my some jinja logic r something else so that i can insert some conditions like if file is image: use <img> tag else: use <video> tag