Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, better many 2 many in the admin
is there anyway to improve this in the django admin panel? As you can see its a simple Many2Many field. -
Django - NoReverseMatch error not a valid function or pattern
The error is Reverse for 'django_with_ocr.ocr.views.list' not found. 'django_with_ocr.ocr.views.list' is not a valid view function or pattern name Exception value here is not a valid function or pattern name. There is also an error 'charmap' codec can't encode character '\ufb01' in position 843: character maps to views.py from django.shortcuts import render from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.urls import reverse from .models import Document from .forms import DocumentForm from django.http import HttpResponse import csv import ipdb from Cython.Compiler.Buffer import context try: import Image except ImportError: from PIL import Image import pytesseract global i i = 0 def list(request): global i # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() i += 1 # import ipdb;ipdb.set_trace() d = Document.objects.get(id=i) #print d.docfile k=pytesseract.image_to_string(Image.open(d.docfile)) #print k handle = open('data.txt', 'a+') handle.write(k) handle.close() txt_file = r"data.txt" csv_file = r'mycsv.csv' in_txt = csv.reader(open(txt_file, "r"), delimiter = ' ') out_csv = csv.writer(open(csv_file, 'w', encoding='utf-8')) out_csv.writerows(in_txt) # Redirect to the document list after POST return HttpResponseRedirect(reverse('django_with_ocr.ocr.views.list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render … -
Delete database records depending on JSON
I'm using django and I have this default sqlite database. I'm having troubles deleting database records that aren't in the JSON I get daily from an API. Context: I'm using an API to add release dates to my database in django. If this release date doesn't exist but exists in the json; add it in, if it exists in both update it, but now how do I delete the release date if it exists in my databse but no longer exists in the new JSON? Thank you, here's what I have so far: for release_date_object in game_object['release_dates']: release_date = ReleaseDate.objects.filter(game=game.id, platform=release_date_object['platform'], region=release_date_object['region']) if release_date.exists(): # Update it! continue # important elif release date exists in the db, but not in the json: # delete it # if this game has already been added, but the release date isn't in the json it means you must delete it else: # if release date exists in the json, but doesn't exist in the db; add it in # create -
"Error decoding Signature" in Django. When user tries to access the endpoint after providing the access token then this error message is displayed
Scenario: I have created API in Django and also implemented JWT Authentication. I have implemented the criteria for entering the access token when the user tries to access the API endpoint. The user can get the refresh token and access token after successful login with username and password. And with the help of the refresh token, user can get the access token as well. Problem: When the user tries to access the endpoint after providing the Authorization and Bearer in the header (Postman) then I'm getting the error message called "Error decoding signature." What can be the solution for this? Note: I'm using Django 1.11.7 version and jwt_authentication. -
Django - System architecture for reusing user registration form on multiple pages
I was figuring how to reuse the same registration form and view on multiple templates and pages, and in different formats. E.g. on the page, in a modal etc. I am however some trouble in figuring out the best practice for solving this problem. One thing I am actively trying to avoid is repeating myself, but I can't seem to find a solution that is satisfying enough. At the moment I have one central view that handles user registrations that looks like this. At the moment it can only handle to output one form on the signup_form template, but I want to extend that to the index page and be able to be outputted in a modal as well. Views.py def signup(request): template_name = 'core/authentication/signup_form.html' custom_error_list = [] if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): #Check for duplciate email email = form.cleaned_data.get('email') username = form.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).exists(): custom_error_list.append("A user with that email already exists") else: user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your StockPy Account' sender = '' #Insert sender address here message = render_to_string('core/authentication/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) user.email_user(subject, message) return redirect('authentication:account_activation_sent') else: … -
Adding Unique Slug in Django
I'm trying to add a slug field in my school project, Here's what I tried in my model, def pre_save_receiver(sender, instance, *args, **kwargs): slug = slugify(instance.title) exists = Data.objects.filter(slug=slug).exists() if exists: instance.slug = "%s-%s" % (slug, instance.id) else: instance.slug = slug pre_save.connect(pre_save_receiver, sender=Data) Everything is working fine but the problem is that it's adding ID in slug field behind even if it's Unique. How can I fix that? Thank You . . . -
django RestFrameWork _OneToOneField serializer .create()
I have two models in my django project. AdIfo, and AdGame. The model Adgame has OneToOne relation with AdIfo.in django admin panel. I can build properly Object AdGame model. But when I try making in serializer the error is :IntegrityError FOREIGN KEY constraint failed Models.py: class AdIfo(models.Model): address = models.TextField(max_length=250) price = MoneyField(max_digits=12, decimal_places=0, default_currency="IRR") phonenumber = models.CharField(validators=[phone_regex], max_length=17, null=True, blank=True) ad_status = models.BooleanField() class AdGame(models.Model): CONSOLE_GAME = ( ('XBX', 'Xbox'), ('PS4', 'Play Station 4'), ('PC', 'Personal Computer'), ) GAME_REGION = ( ('1', 'USA'), ('2', 'Europe'), ('3', 'MiddleEast'), ('j', 'Japan'), ('4', 'Australia'), ('N', 'Unknown') ) title = models.CharField(max_length=25) game = models.ForeignKey(Game, on_delete=models.CASCADE) console = models.CharField(max_length=3, choices=CONSOLE_GAME) game_region = models.CharField(max_length=1, choices=GAME_REGION) ad_info = models.OneToOneField(AdIfo, related_name='ad_info', primary_key=True, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=True) owner = models.ForeignKey(User, related_name='ad_owner', on_delete=models.CASCADE) image = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, variations={ 'large': (800, 600), 'medium': (600, 400), 'small': (300, 200), 'thumbnail': (100, 100, True), }) publish_date = models.DateTimeField(auto_now=True) def __str__(self): return self.title serializers.py class AdInfoSerializer(serializers.ModelSerializer): """ad information serialization""" phonenumber = serializers.IntegerField() class Meta: model = AdIfo fields = "__all__" class AdGameSerilizer(serializers.ModelSerializer): ''' Ad model serialization ''' ad_info = AdInfoSerializer(required=True) console = serializers.ChoiceField(choices=AdGame.CONSOLE_GAME) game_region = serializers.ChoiceField(choices=AdGame.GAME_REGION) owner = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) image = serializers.ImageField() class Meta: model = AdGame fields = [ 'ad_info', … -
How to give choice to froms.ChoiceField for Django forms
class CountryLevelOptimization(forms.Form): name = forms.CharField() country = forms.ChoiceField(widget=forms.Select, choices=(('A','a'),('B','b'))) Above is my Django form in which country is a ChoiceField Following is my python code. def Homepage(request): choices = (('Country1','India'),('Country2','USA')) form = CountryLevelOptimization() # How to pass choices to the form['country'] return render(request,"Dummy.html",{"form":form}) How can i pass choices to the country in from the view Homepage ? please help me with this. -
Attribute error in extending django user model?
I have done this before and got it working fine. Is this because i'm using django2.0? models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) .... @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() I get the error AttributeError: 'User' object has no attribute 'profile'. I don't get it? -
django count queryset field in listview template
Question which i am stuck with I want to count venlist.Status which is equal to Active and show it in some html tag Please let me know if you need more details on my question as this is my first post and been searching for it in the library fromm almost 4 hours Models.py VendorCH= [ ('Active', 'Active'), ('BlackList', 'BlackList'), ] class VendorModel(models.Model): Name=models.CharField(unique=True,max_length=40) President=models.CharField(unique=True,max_length=40) Status=models.CharField(max_length=40,choices=VendorCH,default='Active') Forms.py class VendorForm(forms.ModelForm): class Meta: model = VendorModel exclude=['VendorStatus'] views.py class VendorCreateView(SuccessMessageMixin,CreateView): template_name = "ePROC/Administration/Vendor_Create.html" model=VendorModel fields=['Name','President'] success_message = "Record was created successfully" success_url = reverse_lazy('ePROC:ePROCHOME') def form_valid(self, form): form.instance.Status = 'Active' return super(VendorCreateView, self).form_valid(form) List_Template.html <table class="table table-hover"> <thead> <th> Vendor Name</th> <th> President</th> <th> Status</th> </thead> <tbody> {% for venlist in object_list %} <tr> <td>{{ venlist.VendorName }}</td> <td>{{ venlist.President}}</td> <td>{{ venlist.Status}}</td> </tr> {% endfor %} <tbody> </table> -
Django ,supervisord,and gunicorn setting environment variables and accessing in django settings
I am using gunicorn and django in python virtual environment. os: ubuntu 14.04 gunicorn : 19.0 django : 1.10 supervisor In my setings file I am reading variable from virtual environment My prod_settings.py DB_NAME = os.environ.get("USER_NAME") DB_PASSWORD = os.environ.get("MONGO_PASSWORD") DB_URI_STRING = os.environ.get("MONGO_URI_STRING") I have set environment variable through .bashrc In virtual environment, if I run python manage.py runserver then everything is working fine. my gunicorn.bash NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=django_project.settings.prod_settings DJANGO_WSGI_MODULE=django_project.wsgi echo "starting $NAME as `whaoami` " # Activate the virtual environment cd $DJANGO_DIR source /home/sachin/Documents/django_project/virtEnv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGO_DIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR= $(dirname $SOCK_FILE) test -d $RUNDIR || mkdir -p $RUNDIR #Start Django Unicorn #Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCK_FILE \ --log-level=debug \ --log-file=- if I run this script directly in console everything working but when I run this script using supervisorctl then key error is occuring . For ex "USER_NAME" keyerror my supervisor_config script [program:django_project] command = /home/sachin/Documents/django_project/gunicorn_start.bash user = sachin stdout_logfile = /home/sachin/Documents/django_project/logs/gunicorn_supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 sudo supervisorctl start django_project same code is working with supervisor also if hardcode … -
Unique Slug Field: Django
I'm trying to add a slug field, Here's what I tried in my model, slug = models.SlugField(unique=True) def pre_save_receiver(sender, instance, *args, **kwargs): slug = slugify(instance.title) exists = Data.objects.filter(slug=slug).exists() if not exists: instance.slug = slug else: instance.slug = "%s-%s" % (slug, instance.id) pre_save.connect(pre_save_receiver, sender=Data) Problem is that it's adding the ID in slug field behind title no matter even if it's a very Unique title. How can I fix that? Thank YOU :) -
How to resolve Django error 'index' is not a valid tag library: Template library index not found, tried"
I have write down a new templatetag for django under "table" app inside "myproject" folder, further another folder has been created inside the "table" app folder as "tamplatetages", further two files, "__init__.py" and "index.py" have been created. Template tag was created to get list item from the list index as we do in regular python code ex: ls = [a, b, c,d] nl = [w, x,y,z] for i,x in enumerate(ls): print x, nl[i] this is my tamplatetag file"index.py" from django import template register = template.Library() @register.filter def index(List, i): return List[int(i)] and this is how I have incorporated new tamplatetags inside my template: {% load index %} <ul class="sidebar-categories"> {% for news in text_list %} <a href="{{ link_list|index:forloop.counter0 }}"> <b> {{news}}</b> <br> {% endfor %} </ul> but its shows error like this: 'index' is not a valid tag library: Template library index not found, tried django.templatetags.index,django.contrib.admin.templatetags.index,django.contrib.staticfiles.templatetags.index,import_export.templatetags.index Request Method: GET Request URL: http://127.0.0.1:8000/cholera/ Django Version: 1.8 Exception Type: TemplateSyntaxError Exception Value: 'index' is not a valid tag library: Template library index not found, tried django.templatetags.index,django.contrib.admin.templatetags.index,django.contrib.staticfiles.templatetags.index,import_export.templatetags.index Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py in load, line 1159 Python Executable: /usr/bin/python Python Version: 2.7.12 while, I am able to successfuly import it on the Django shell >>> … -
Bokeh zoom and pan bounds acting strange
I have a Bokeh plot that looks like this: plot = figure(plot_width=1000, plot_height=300, y_range=(0, 1), x_range=Range1d(1, len(fasta_object.sequence()), bounds=(1, len(fasta_object.sequence()))), tools="xpan,xwheel_zoom,box_zoom,save,reset", active_scroll="xwheel_zoom", title=fasta_object.header(), y_axis_label='Score', x_axis_label='Position') What i want is to be able to wheel scroll only on the x axis, and dont go outside the possible bounds. The code above does exactly this, however when i zoom in with scrolling and out again i cant scroll out to the "full" picture. The scrolling out stops at some seemingly random number. Why is this happening? PS: The figure is rendered inside Django, if thats a possible source of this error. -
How to initialize java script when you have two or more base HTML
I have two base HTML page one with navbar and one without navbar and i am using metralized css and it has js file to be initialized in order many functions in UI level i need the js files to accessed in all html page. How to implement that . i am getting following error: VM798 jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. send @ VM798 jquery-3.2.1.min.js:4 VM806:6 Velocity is already loaded. You may be needlessly importing Velocity again; note that Materialize includes Velocity. VM798 jquery-3.2.1.min.js:2 jQuery.Deferred exception: $(...).sideNav is not a function TypeError: $(...).sideNav is not a function at HTMLDocument.<anonymous> (<anonymous>:4:26) at j (https://code.jquery.com/jquery-3.2.1.min.js:2:29999) at k (https://code.jquery.com/jquery-3.2.1.min.js:2:30313) undefined r.Deferred.exceptionHook @ VM798 jquery-3.2.1.min.js:2 VM798 jquery-3.2.1.min.js:2 Uncaught TypeError: $(...).sideNav is not a function at HTMLDocument.<anonymous> (<anonymous>:4:26) at j (VM798 jquery-3.2.1.min.js:2) at k (VM798 jquery-3.2.1.min.js:2) VM807 jquery-3.2.1.min.js:2 jQuery.Deferred exception: $(...).sideNav is not a function TypeError: $(...).sideNav is not a function at HTMLDocument.<anonymous> (<anonymous>:4:26) at j (https://code.jquery.com/jquery-3.2.1.min.js:2:29999) at k (https://code.jquery.com/jquery-3.2.1.min.js:2:30313) undefined r.Deferred.exceptionHook @ VM807 jquery-3.2.1.min.js:2 VM807 jquery-3.2.1.min.js:2 Uncaught TypeError: $(...).sideNav is not a function at HTMLDocument.<anonymous> (<anonymous>:4:26) at j (VM798 jquery-3.2.1.min.js:2) at k (VM798 jquery-3.2.1.min.js:2) … -
How to style django-multiselectfield with CSS
I am using 'django-multiselectfield' in my model form so users can select multiple 'areas' in my form. What I want to know now is how can I style the multiselectfield using css. I have tried simply adding a class to the form field in my template like I normally do with all the other types of model fields, but no luck: {% render_field form.area class="area" %} Any help would be much appreciated. -
python3 django manage.py runserver error
I have a project in AWS cloud9. I tried to login via LinkedIn or Facebook, i use django. When i run the command : python manage.py runserver 0.0.0.0:8080 i get Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.4/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.4/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.4/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/home/ec2-user/environment/gowith/django_social_project/django_social_project/settings.py", line 17, in <module> from config import * File "/usr/local/lib/python3.4/site-packages/config.py", line 733 except Exception, e: ^ SyntaxError: invalid syntax -
Execute code after celery finishes a tasks
I'm using Django 2.0, Python 3.6 and Celery 4.1 After celery is finishing a task, I want to execute a code that do an update in the database. How can I do that ? -
Django - How to add a file during model save?
I'm trying to create and save a csv file as part of a save and then associate the file to the record. This is my model class ReOrder (models.Model): product = models.ForeignKey( Product, ) order_quantity = models.IntegerField( default = 0 ) order_date = models.DateField( default = datetime.datetime.now() ) received = models.BooleanField( default = False ) order_file = models.FileField( upload_to = 'reorder_documents/', null = True, blank = True ) def __unicode__(self): return u'%s' % (self.product) def save(self, *args, **kwargs): # create the text file filename = str(self.product)+'_'+str(self.order_date)+".csv" path = os.path.join(MEDIA_ROOT, 'reorder_documents', filename) print path f = open(path, 'wrb') f.truncate() writer = csv.writer(f) writer.writerow((self.product, self.order_quantity)) f.close() self.order_file = ContentFile(f) #save everything super(ReOrder, self).save(*args, **kwargs) # Call the "real" save() method. This creates and saves the file exactly where I want it but doesn't save it to the model. How do I do that? -
Scheduling with Celery - Issue KeyError
I'm trying to schedule tasks using Celery. I have the following code in the django folder (where are settings.py): in celery.py app.conf.beat_schedule = { 'add-every-3-minutes': { 'task': 'notes.tasks.add', 'schedule': crontab(minute='*/2'), # execute every 2 minutes 'args': (16, 16) }, } In notes folder of the django app notes I have the following code: @task(name="sum_two_numbers") def add(x, y): return x + y The error that I have is: line 561, in on_task_received strategy = strategies[type_] KeyError: 'notes.tasks.add' I'm on Django 2.0 and python 3.6, using Celery 4.1.0; Without schedule I tested in shell and it works. I suppose is related to the path to the tasks, but I don't understand why. -
Django 'datetime.datetime' object is not callable
I just want to update my model : My view : message = InboxRecruiting.objects.get(id=id_message, on_team=team, is_removed=False) message.update(is_read_team=True) My model : class InboxRecruiting(models.Model): on_team = models.ForeignKey(Team, verbose_name="Equipe") from_user = models.ForeignKey(User, verbose_name="De", related_name='from_user') to_user = models.ForeignKey(User, verbose_name="Vers", related_name='to_user') is_read_team = models.BooleanField(default=False, verbose_name="Lu (auteur)") is_read_player = models.BooleanField(default=False, verbose_name="Lu (destinataire)") is_removed = models.BooleanField(default=False, verbose_name="Supprimé") is_accepted = models.NullBooleanField(default=None, verbose_name="Accepté") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return str(self.date) It returns an error : 'datetime.datetime' object is not callable Thank you -
remove duplicates from the list of a model instances
Based on the post: Django comparing model instances for equality I am trying to remove the duplicates from my list of instance (Which have not been saved yet and I assume their 'id' to be None) the code is: a = list() a.append(relation_list.pop()) for x in relation_list: duplicate = False for z in a: if z is x: #or if z.attrib1 == x.attrib1 and z.attrib2 == x.attrib2: duplicate = True if not duplicate: a.append(x) However, given the attribs being equal the line duplicate = True never get executed. What am I missing? Is there a more efficient way to achieve this? (inspired from this post using "in relation_list" either does not work. -
django.db.utils.ProgrammingError: column "questions" is of type character varying[] but default expression is of type integer
class college(models.Model): image = models.ImageField(upload_to='college_image/',default=None) name = models.CharField(max_length=100) email = models.CharField(max_length=100,unique=True) password = models.CharField(max_length=500) add_field = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=200) zipcode = models.CharField(max_length=10) phone = models.CharField(max_length=10, validators=[RegexValidator(r'^[789]\d{9}$')]) status = models.BooleanField(default = True) last_date = models.DateTimeField() is_active = models.BooleanField(default = False) reg_time = models.DateTimeField(auto_now_add=True,blank=True) questions = ArrayField(models.CharField(max_length=500),blank=True) def __str__(self): return self.email Error occurred when I added questions field in college model and used command 'python manage.py migrate' HINT(shown after the command): You will need to rewrite or cast the expression -
Filtering starting from a Foreign key users that are not staff combined with other filters
I have the following model: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='activity', sent_at = models.DateTimeField(blank=True, null=True) on_delete=models.CASCADE) I need a query that exclude all users that are not staff and sent is null. So I tried to use exclude: Post.object.all().exclude(user.is_staff=True) and I get the following error: keyword can't be an expression -
MySQL trigger condition
Consider the following scenario where users can enable/disable MySQL triggers using a web interface. I am creating a session variable once the user opens a specific web page by executing the following command: SET @vsAge = 0 This variable is then used inside a BEFORE INSERT trigger: BEGIN IF (@vsAge = 1) THEN IF new.age < 0 THEN SET new.age = 0; END IF; END IF; END However when I run my Django server and create this variable, my trigger doesn't work properly, running the command SELECT * FROM performance_schema.user_variables_by_thread is showing me that this variable does exist, and the problem can't be with the code since if I create this variable using MySQL workbench, everything works fine, so the problem is probably somewhere on the server. How does django handle database connections and sessions, I'm guessing somewhere in my code the database connection gets closed and this variable is stored in a different session. Is it possible to force django to use a single MySQL session? I use the django database api for some operations and for making variables I am using: class Database: def __init__(self): self.con = None def connect(self): self.con = mdb.connect('localhost', 'root', 'password', 'dbname') def trigger_toggle(self, …